iText html2pdf change size of the output PDF - java

How to change output PDF page size when converting it from HTML with iText html2pdf library? Tried this code:
ConverterProperties properties = new ConverterProperties();
MediaDeviceDescription description = MediaDeviceDescription.createDefault();
description.setHeight(1024);
description.setWidth(1024);
properties.setMediaDeviceDescription(description);
HtmlConverter.convertToPdf(new File(htmlSource), new File("outputFile.pdf"), properties);
but, looks like it does not work, my output page is still A4

Use one of the HtmlConverter's methods which take a PdfDocument instance as a parameter and set the needed page size on it with setDefaultPageSize method.
For example,
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(destinationPath));
pdfDoc.setDefaultPageSize(new PageSize(1500, 842));
HtmlConverter.convertToPdf(new FileInputStream(sourcePath), pdfDoc);

Related

iText7: Can we specify multiple base Uri while converting html to pdf?

I'm currently using iText 7 to convert HTML to PDF using URL.
The problem is that on the page that I want to convert there are external css files and images that are not coming from the same source:
For example I have an external css file whose path is baseUri1/path-to-file/file.css and I have other images that are from baseUri2/path-to-file2/img.jpg
Here's the code that I am actually using for the conversion
String ADDRESS = "https://www.monagentdevoyages.fr/product?s_pid=4964";
//** The target folder for the result. *//*
String TARGET = "target/results/ch07/";
//** The path to the resulting PDF file. *//*
String DEST = String.format("%surl2pdf_print.pdf", TARGET);
PdfWriter writer = new PdfWriter(DEST);
PdfDocument pdf = new PdfDocument(writer);
PageSize pageSize = new PageSize(850, 1700);
pdf.setDefaultPageSize(pageSize);
ConverterProperties properties = new ConverterProperties();
MediaDeviceDescription mediaDeviceDescription =
new MediaDeviceDescription(MediaType.PRINT);
mediaDeviceDescription.setWidth(pageSize.getWidth());
properties.setMediaDeviceDescription(mediaDeviceDescription);
properties.setBaseUri("https://www.monagentdevoyages.fr/");
HtmlConverter.convertToPdf(new URL(ADDRESS).openStream(), pdf, properties);
When I run this code, I get the following error :
20 --- [nio-9001-exec-9] c.i.s.r.resource.ResourceResolver : Unable to retrieve image with given base URI (https://www.monagentdevoyages.fr/) and image source path (null)
Any idea how to solve this problem please ?

Svg Image is not properly render in the pdf

[]
1[]2]3
Here is my code to add svg image in the pdf using itext 7.1.3 and also using SVGConventer.The image not properly rendered, i am not able understand where and what is the problem? Can anyone help me. Thanks in advance.
PdfWriter writer = new PdfWriter(new FileOutputStream("/home/users/Documents/pdf/new.pdf"));
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
URL svgUrl = new File(svg).toURI().toURL();
doc.add(new Paragraph("new pikachu"));
Image image = SvgConverter.convertToImage(svgUrl.openStream(), pdfDoc);
doc.add(image);
doc.close();

How to save charts in same pdf file using Xchart and VectorGraphics2D

I create chart using Xchart and save it as PDF file using VectorGraphics2D as follows:
VectorGraphicsEncoder.saveVectorGraphic(chart, "chart_name", VectorGraphicsFormat.PDF);
However I need to save several charts in the same PDF file. Is there any way of doing it using iText?
ProcessingPipeline g = null;
g = new PDFGraphics2D(0.0, 0.0, chart.getWidth(), chart.getHeight());
chart.paint(g, chart.getWidth(), chart.getHeight());
FileOutputStream file1 = new FileOutputStream(addFileExtension("doc_name", VectorGraphicsFormat.PDF));
Document doc = new Document(PageSize.A4.rotate());
PdfWriter writer = PdfWriter.getInstance(doc, file1);
doc.open();
However I fail when I add the g to the document. How do I fix this?
You can save an image with desired grid in one image using :
BitmapEncoder.saveBitmap(
Arrays.asList(new Chart[]{chart1, chart2, chart3, chart4}), 2,2, "./cumulative", BitmapEncoder.BitmapFormat.PNG);
where 2,2 is the row and col size.
After getting this image with 4 charts you can export it in a PDF.

How to set PDF page size A4 when we use ITextRenderer to generate PDF from thymeleaf HTML template?

How to set PDF page size A4 when we use ITextRenderer to generate PDF from thymeleaf HTML template ?
I have generated PDF but page size is not proper, how to set page size A4 ITextRenderer library in JAVA
ClassLoaderTemplateResolver templateResolver = new
ClassLoaderTemplateResolver();
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
Context context = new Context();
context.setVariable("name", "Thomas");
String html = templateEngine.process("templates/Quote", context);
OutputStream outputStream = new FileOutputStream("message.pdf");
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(html);
renderer.layout();
renderer.createPDF(outputStream,true);
outputStream.close();
Please be aware that you are using FlyingSaucer, not iText.
FlyingSaucer is a product that internally uses (a very old version of) iText.
You are immediately cutting yourself off from 10+ years of bugfixes and developments.
If you are comfortable going for just iText, the best way of solving this issue is with pdfHTML.
It's an add-on we wrote to the iText7 core library that is specifically designed to convert HTML into PDF.
Simple example:
File src = new File("source_html_file.html");
File dest = new File("target_pdf_file.pdf");
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdf, PageSize.A4);
InputStream stream = new FileInputStream(src);
ConverterProperties converterProperties = new ConverterProperties();
FontProvider dfp = new DefaultFontProvider(true, true, true);
converterProperties.setFontProvider(dfp);
HtmlConverter.convertToPdf(stream, pdf, converterProperties);
Check out the tutorials online for more information
https://developers.itextpdf.com/content/itext-7-examples/itext-7-converting-html-pdf
To fix this issue using jsoup, xhtmlrenderer from flying-saucer-pdf-openpdf just set this in your html-document:
#page {
size: A4;
}

How to copy/move AcroForm fields from one document to new blank one using IText5 or IText7?

I need to copy whole AcroForm including field positions and values from template PDF to a new blank PDF file. How can I do that?
In short words - I need to get rid of "background" from the template and leave only filed forms.
The whole point of this is to create a PDF with content that would be printed on pre-printed templates.
I am using IText 5 but I can switch to 7 if usefull examples would be provided
After a lot of trial and error I have found the solution to "How to copy AcfroForm fields into another PDF". It is a iText v7 version. I hope it will help somebody someday.
private byte[] copyFormElements(byte[] sourceTemplate) throws IOException {
PdfReader completeReader = new PdfReader(new ByteArrayInputStream(sourceTemplate));
PdfDocument completeDoc = new PdfDocument(completeReader);
ByteArrayOutputStream out = new ByteArrayOutputStream();
PdfWriter offsetWriter = new PdfWriter(out);
PdfDocument offsetDoc = new PdfDocument(offsetWriter);
offsetDoc.initializeOutlines();
PdfPage blank = offsetDoc.addNewPage();
PdfAcroForm originalForm = PdfAcroForm.getAcroForm(completeDoc, false);
// originalForm.getPdfObject().copyTo(offsetDoc,false);
PdfAcroForm offsetForm = PdfAcroForm.getAcroForm(offsetDoc, true);
for (String name : originalForm.getFormFields().keySet()) {
PdfFormField field = originalForm.getField(name);
PdfDictionary copied = field.getPdfObject().copyTo(offsetDoc, false);
PdfFormField copiedField = PdfFormField.makeFormField(copied, offsetDoc);
offsetForm.addField(copiedField, blank);
}
offsetDoc.close();
completeDoc.close();
return out.toByteArray();
}
Did you check the PdfCopyForms object:
Allows you to add one (or more) existing PDF document(s) to create a new PDF and add the form of another PDF document to this new PDF.
I didn't find an example, but you could try something like this:
PdfReader reader1 = new PdfReader(src1); // a document with a form
PdfReader reader2 = new PdfReader(src2); // a document without a form
PdfCopyForms copy = new PdfCopyForms(new FileOutputStream(dest));
copy.AddDocument(reader1); // add the document without the form
copy.CopyDocumentFields(reader2); // add the fields of the document with the form
copy.close();
reader1.close();
reader2.close();
I see that the class is deprecated. I'm not sure of that's because iText 7 makes it much easier to do this, or if it's because there were technical problems with the class.

Categories

Resources