Working with PDF Images
31 Mar 2020 / 2 minutes to read
Images are supported through the PdfImage
class, which is an abstract base class that provides functionality for PdfBitmap
class.
Inserting an image in PDF document
The following raster images are supported in Flutter PDF:
- JPEG
- PNG
You can load image data in PdfBitmap
object to draw the images using the drawImage
method of the PdfGraphics
class. The image data can be initialized as list of bytes or base64 string format.
The following code snippet shows how to draw an image to the PDF document.
//Create a new PDF document
PdfDocument document = PdfDocument();
//Adds a page to the document
PdfPage page = document.pages.add();
//Draw the image
page.graphics.drawImage(
PdfBitmap(File('image.jpg').readAsBytesSync()),
Rect.fromLTWH(
0, 0, page.getClientSize().width, page.getClientSize().height));
//Saves the document
File('Output.pdf').writeAsBytes(document.save());
//Disposes the document
document.dispose();
Applying transparency and rotation to the image
You can add transparency and rotation to the image using the setTransparency
and rotateTransform
methods of PdfGraphics
respectively. This is explained in the following code snippet.
//Create a new PDF document
PdfDocument document = PdfDocument();
//Adds a page to the document
PdfPage page = document.pages.add();
//Save the current graphics state
PdfGraphicsState state = page.graphics.save();
//Translate the coordinate system to the required position
page.graphics.translateTransform(20, 100);
//Apply transparency
page.graphics.setTransparency(0.5);
//Rotate the coordinate system
page.graphics.rotateTransform(-45);
//Draw image
page.graphics.drawImage(
PdfBitmap(File('image.jpg').readAsBytesSync()),
Rect.fromLTWH(
0, 0, page.getClientSize().width, page.getClientSize().height));
//Restore the graphics state
page.graphics.restore(state);
//Saves the document
File('Output.pdf').writeAsBytes(document.save());
//Disposes the document
document.dispose();
Was this page helpful?
Yes
No
Thank you for your feedback!
Thank you for your feedback and comments. We will rectify this as soon as possible!
An unknown error has occurred. Please try again.
Help us improve this page