Skip to content

Instantly share code, notes, and snippets.

@aspose-com-gists
Created April 15, 2021 00:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aspose-com-gists/598e9dac78d02bfad5844c7f4feca86c to your computer and use it in GitHub Desktop.
Save aspose-com-gists/598e9dac78d02bfad5844c7f4feca86c to your computer and use it in GitHub Desktop.
Convert Image to PDF in Java
// Instantiate Document Object
Document doc = new Document();
// Add a page to pages collection of document
Page page = doc.getPages().add();
// Load the source image file to Stream object
java.io.FileInputStream fs = new java.io.FileInputStream("source.png");
// Set margins so image will fit, etc.
page.getPageInfo().getMargin().setBottom(0);
page.getPageInfo().getMargin().setTop(0);
page.getPageInfo().getMargin().setLeft(0);
page.getPageInfo().getMargin().setRight(0);
page.setCropBox(new Rectangle(0, 0, 400, 400));
// Create an image object
Image image1 = new Image();
// Add the image into paragraphs collection of the section
page.getParagraphs().add(image1);
// Set the image file stream
image1.setImageStream(fs);
// Save resultant PDF file
doc.save("Image2PDF.pdf");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment