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 ?
Related
I need to transform HTML to a doc file, the HTML is filled with custom information and the images and CSS change depending on what is request.
I'm trying to use Apache POI for this, but I'm having an error
`
org.apache.poi.xwpf.converter.core.XWPFConverterException: java.lang.IllegalStateException: Expecting one Styles document part, but found 0
at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.convert(XHTMLConverter.java:72)
at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.doConvert(XHTMLConverter.java:58)
at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.doConvert(XHTMLConverter.java:38)
at org.apache.poi.xwpf.converter.core.AbstractXWPFConverter.convert(AbstractXWPFConverter.java:45)
My code is this:
// Load the HTML file
//Doc file
String htmlFile = "pathToHtml/file.html";
//String htmlFile = parseHTMLTemplate(disputeLetterDetails, template, fileExtension);
//new File(htmlFile);
//File file = new FileReader(htmlFile);
Path path = Path.of(htmlFile);
OutputStream in = new FileOutputStream(htmlFile, true);
// Create a new XWPFDocument
XWPFDocument document = new XWPFDocument();
// Set up the XHTML options
XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(new File("./images/")));
options.setExtractor(new FileImageExtractor(new File("./images/")));
// Convert the HTML to XWPFDocument
XHTMLConverter.getInstance().convert(document, in, options);
// Save the document to a .doc file
FileOutputStream out = new FileOutputStream("pathToHtml/OUT_from_XHTML_TEST.docx");
document.write(out);
out.close();
`
I want to get a docx file from an HTML file with the same styles but I'm getting this error `
org.apache.poi.xwpf.converter.core.XWPFConverterException: java.lang.IllegalStateException: Expecting one Styles document part, but found 0
at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.convert(XHTMLConverter.java:72)
at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.doConvert(XHTMLConverter.java:58)
at org.apache.poi.xwpf.converter.xhtml.XHTMLConverter.doConvert(XHTMLConverter.java:38)
at org.apache.poi.xwpf.converter.core.AbstractXWPFConverter.convert(AbstractXWPFConverter.java:45)
`
I am merging PDF content using PDFMergerUtility in Java.
PDFMergerUtility bundle= new PDFMergerUtility();
bundle.addSource(new ByteArrayInputStream(contentService.retrieveData(transaction1);
bundle.addSource(new ByteArrayInputStream(contentService.retrieveData(transaction2);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()
bundle.setDestinationStream(outputStream); // setting outputstream
bundle.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
return outputStream.toByteArray(); // returning result
But by default it is opening on the last page of PDF when I try to open the resultant PDF. I am not using PDocument for these as
these are entity based documents. Due to this unable to use this below method. Can you please suggest any approach to directly set the opened page number in PDFMergerUtility.
PDPageXYZDestination destination = new PDPageXYZDestination();
destination .setPageNumber(num);
PDActionGoTo action = new PDActionGoTo();
action.setDestination(destination );
pdf.getDocumentCatalog().setOpenAction(action);
I am running into strange issue with generated pdf's from iText7. The generated pdf's are opening properly in Adobe reader and Chrome browser. But the same pdf is opening partially in the Firefox browser. I am getting the below message in Firefox. The strange thing is other pdf, which are not generated via iText are properly rendering in firefox.
Java code
public static byte[] createPdf(List<String> htmlPages, PageSize pageSize, boolean rotate) throws IOException {
ConverterProperties properties = new ConverterProperties();
// Register classpath protocol handler to be able to load HTML resources from class patch
org.apache.catalina.webresources.TomcatURLStreamHandlerFactory.register();
properties.setBaseUri("classpath:/");
// properties.setBaseUri(baseUri);
FontProvider fontProvider = new DefaultFontProvider(true,false,false);
properties.setFontProvider(fontProvider);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
PdfDocument pdf = new PdfDocument(new PdfWriter(byteArrayOutputStream));
PdfMerger merger = new PdfMerger(pdf);
for (String htmlPage : htmlPages) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfDocument temp = new PdfDocument(new PdfWriter(baos));
if(rotate) {
temp.setDefaultPageSize(pageSize.rotate()); /** Page Size and Orientation */
} else {
temp.setDefaultPageSize(pageSize); /** Page Size and Orientation */
}
HtmlConverter.convertToPdf(htmlPage, temp, properties);
temp = new PdfDocument(new PdfReader(new ByteArrayInputStream(baos.toByteArray())));
merger.merge(temp, 1, temp.getNumberOfPages());
temp.close();
}
pdf.close();
byteArrayOutputStream.flush(); // Tried this
byteArrayOutputStream.close(); // Tried this
byte[] byteArray = byteArrayOutputStream.toByteArray();
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
try (FileOutputStream fileOuputStream = new FileOutputStream("D:\\Labels\\Label_"+timestamp.getTime()+".pdf")){
fileOuputStream.write(byteArray);
}
return byteArray;
}
Thanks in advance.
Edit 1:
You can find pdf and html/css for reproducing issue here.
When you embedded the images into your html using base64 URIs, something weird happened to the image of the barcode: Instead of the 205×59 bitmap image in labelData/barcode.png you embedded a 39578×44 image! (Yes, an image nearly a thousand times wider than high...)
The iText HtmlConverter embedded that image just fine but apparently Firefox has issues displaying an image with those dimensions even though (or probably because?) it is transformed into the desired dimensions (about four times wider than high) on the label. At least my Firefox installation stops drawing label contents right here. (Beware, the order of drawing in the PDF content is not identical to the of the HTML elements; in particular in the PDF the number 3232000... is drawn right before the barcode, not afterwards!)
On Firefox:
On Acrobat Reader:
Thus, you may want to check the transformation of the bar code image to the base64 image URI in your HTML file.
This might be common question, but I didn't found exact solution.
I have a JavaFX application which creates PDF file (using iText 7) using data from cloud sql server.
However, this file is now saved in my specified file path.
I want my user to specify where he/she wants to save that file.
String dest = "itextData//singleLR.pdf";
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf);
Now here, the path dest is already specified. I want it to be specified by user.
Expected output
//File browsing code on button click
//Got String in variable user_specified_path
String dest = user_specified_path;
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf);
As suggested by #VGR , I used JavaFX FileChooser.
However, instead of fileChooser.showOpenDialog(scene) , I used fileChooser.showSaveDialog(scene);
showOpenDialog() is used to open existing file.
showSaveDialog() is used to create new file
So my code goes like below,
print.setOnAction(event -> {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Save PDF File");
fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("PDF File", "*.pdf"));
File selectedFile = fileChooser.showSaveDialog(print.getScene().getWindow());
if (selectedFile != null) {
String dest = selectedfile.getAbsolutePath();
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdf = new PdfDocument(writer);
Document document = new Document(pdf);
//DOCUMENT WRITING CODE BEGINS
}
}
For reference -> Saving File with FileChooser in JavaFX
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);