I have created a Document with iText, and I would like to convert this document (which is saved as a PDF file) to an image. For this I use PDFBox, which wants a PDDocument as input. I use the following code:
@SuppressWarnings("unchecked")
public static Image convertPDFtoImage(String filename) {
Image convertedImage = null;
try {
File sourceFile = new File(filename);
if (sourceFile.exists()) {
PDDocument document = PDDocument.load(filename);
List<PDPage> list = document.getDocumentCatalog().getAllPages();
PDPage page = list.get(0);
BufferedImage image = page.convertToImage();
//Part where image gets scaled to a smaller one
int width = image.getWidth()*2/3;
int height = image.getHeight()*2/3;
BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics2D = scaledImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0, width, height, null);
graphics2D.dispose();
convertedImage = SwingFXUtils.toFXImage(scaledImage, null);
document.close();
} else {
System.err.println(sourceFile.getName() +" File not exists");
}
}
catch (Exception e) {
e.printStackTrace();
}
return convertedImage;
}
At the moment, I load the document from the file which has been saved. But I would like to perform this internally from within Java.
So my question is: how can I convert a Document to a PDDocument?
Any help is greatly appreciated!
What you could do is to save the itext file into a ByteArrayOutputStream, convert that one to a ByteArrayInputStream.
Document document = new Document();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, baos);
document.open();
document.add(new Paragraph("Hello World!"));
document.close();
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
PDDocument document = PDDocument.load(bais);
Of course the file shouldn't be too big, or you'll have memory problems.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With