Monday, 7 March 2022

Convert XML to PDF in Java

An XML file is an Extensible Markup Language file. It is a plain text file that don’t do anything in and of themselves except describe the transportation, structure and storage of data. Converting XML to PDF can make the file easier to share because PDF is a more common and easy-to-access file format. This article will demonstrate how to programmatically convert XML to PDF using Java codes.

DEPENDENCY

First of all, you're required to get the package of a free third-party library called Free Spire.Doc for Java from this link, and add Spire.Doc.jar as a dependency in your Java program. If you use Maven, you can type the following code in the pom.xml file to import the JAR file.

<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url> https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.doc.free</artifactId>
<version>5.2.0</version>
</dependency>
</dependencies>

USING THE CODE

Free Spire.Doc for Java supports converting XML to PDF using the Document.saveToFile() method. You can following the detailed steps below.

l  Create a Document instance.

l  Load an XML sample document using Document.loadFromFile() method.

l  Save the document as a PDF file using Document.saveToFile() method.

import com.spire.doc.Document;
import com.spire.doc.FileFormat;

public class XMLToPDF {
public static void main(String[] args) {
//Create a Document instance
Document document = new Document();
//Load a XML sample document
document.loadFromFile("C:\\Users\\Tina\\Desktop\\sample.xml");
//Save the document to PDF
document.saveToFile("output/XMLToPDF.pdf", FileFormat.PDF );
}
}


No comments:

Post a Comment

Change PDF Versions in Java

In daily work, you might need to change the version of a PDF document you have in order to ensure compatibility with another version which a...