Page 1 of 1

Is there a way we can convert xml to pdf

PostPosted: Thu Feb 18, 2021 11:16 pm
by monika_thakran
Hi Team,

I have extracted xml out of a docx document using below code

Code: Select all
tempDir = correctDirectoryPath(tempDir);
         bytes = IOUtils.toByteArray(inputStream);
         file = new File(tempDir + fileName + this.formatter.format(new Date()) + ".pdf");
         WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new ByteArrayInputStream(bytes));
         VariablePrepare.prepare(wordMLPackage);
         MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
         // write xml content in a file
            try {
                File fileContent = new File(tempDir + fileName + ".xml");
                FileWriter myWriter = new FileWriter(fileContent);
                myWriter.write(documentPart.getXML());
                myWriter.close();
                return fileContent;
            }
            catch (Exception e) {
            }


Is there a way I can directly generate PDF from this xml, would that be faster?

Re: Is there a way we can convert xml to pdf

PostPosted: Mon Feb 22, 2021 4:52 pm
by jason
The MainDocumentPart contains the text of the document, but not its headers/footers, nor styles or numbering or images.

So if all those things are fixed across your documents, and the only thing which changes is the content of your MainDocumentPart, then yes, you could use that to generate a PDF. For example, apply XSLT to convert the MainDocumentPart XML to XSL FO, then use FOP to convert that to PDF. In this approach, your XSLT would add the style information, any headers/footers etc.

If you are doing document templating to create PDFs, another approach would be https://www.docx4java.org/blog/2020/09/ ... ng-xsl-fo/