I'm trying to set the metadata (such as Title or Author) in a PDF file that I'm creating with FlyingSaucer (https://github.com/flyingsaucerproject/flyingsaucer) from an HTML file.
Here's the code that creates the PDF file:
ByteArrayOutputStream out = new ByteArrayOutputStream();
ITextRenderer renderer = new ITextRenderer();
renderer.getFontResolver().addFont("fonts/VERDANA.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
renderer.getFontResolver().addFont("fonts/VERDANAB.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
renderer.getFontResolver().addFont("fonts/VERDANAI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
renderer.getFontResolver().addFont("fonts/VERDANAZ.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
renderer.setDocumentFromString(... HTML as a String ...);
renderer.layout();
renderer.createPDF(out);
FileOutputStream fos = new FileOutputStream(pathPdf);
PdfReader reader = new PdfReader(baos.toByteArray());
PdfStamper stamper = new PdfStamper(reader, fos);
... sets watermark image if available ...
stamper.close();
reader.close();
I've tried getting the PdfDictionary and setting the metadata, getting the info map and setting the metadata, and getting the Document to set the metadata, but I cannot make it work.
You can do it easier. The essence is to get the writer after the createPdf method, and you must not close the document during pdf creation, but you must do it manually at the end:
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(html);
renderer.layout();
renderer.createPDF(outputStream, false);
renderer.getWriter().getInfo().put(PdfName.CREATOR, new PdfString("witek"));
renderer.finishPDF();
Found the solution:
ByteArrayOutputStream out = new ByteArrayOutputStream();
ITextRenderer renderer = new ITextRenderer();
renderer.getFontResolver().addFont("fonts/VERDANA.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
renderer.getFontResolver().addFont("fonts/VERDANAB.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
renderer.getFontResolver().addFont("fonts/VERDANAI.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
renderer.getFontResolver().addFont("fonts/VERDANAZ.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
renderer.setDocumentFromString(... HTML as a String ...);
renderer.layout();
renderer.createPDF(out);
FileOutputStream fos = new FileOutputStream(pathPdf);
PdfReader reader = new PdfReader(baos.toByteArray());
PdfStamper stamper = new PdfStamper(reader, fos);
... sets watermark image if available ...
PdfDictionary info = reader.getTrailer().getAsDict(PdfName.INFO);
info.getKeys().forEach((k) -> {
System.out.println("k: " + k + ", v:" + info.get((PdfName) k));
});
info.put(PdfName.TITLE, new PdfString("Title", PdfObject.TEXT_UNICODE));
info.put(PdfName.AUTHOR, new PdfString("Author", PdfObject.TEXT_UNICODE));
stamper.close();
reader.close();
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