1. 引入依赖
< dependency> < groupId> com. itextpdf< / groupId> < artifactId> itext7- core< / artifactId> < version> 8.0 .1 < / version>
< / dependency>
2. 代码实现
import com. itextpdf. kernel. geom. PageSize ;
import com. itextpdf. kernel. pdf. PdfDocument ;
import com. itextpdf. kernel. pdf. PdfWriter ;
import com. itextpdf. layout. Document ;
import com. itextpdf. layout. element. Paragraph ;
import com. itextpdf. layout. property. TextAlignment ;
import org. w3c. dom. Document ;
import org. w3c. dom. Element ;
import org. w3c. dom. Node ;
import org. w3c. dom. NodeList ; import javax. xml. parsers. DocumentBuilder ;
import javax. xml. parsers. DocumentBuilderFactory ;
import java. io. File ;
import java. io. FileInputStream ;
import java. io. FileNotFoundException ; public class XmlToPdf { public static void main ( String [ ] args) throws Exception { File xmlFile = new File ( "example.xml" ) ; DocumentBuilderFactory dbFactory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder dBuilder = dbFactory. newDocumentBuilder ( ) ; Document doc = dBuilder. parse ( xmlFile) ; doc. getDocumentElement ( ) . normalize ( ) ; PdfWriter writer = new PdfWriter ( "output.pdf" ) ; PdfDocument pdf = new PdfDocument ( writer) ; Document pdfDoc = new Document ( pdf, PageSize . A4 ) ; processNode ( pdfDoc, doc. getDocumentElement ( ) ) ; pdfDoc. close ( ) ; } private static void processNode ( Document pdfDoc, Node node) { if ( node. getNodeType ( ) == Node . ELEMENT_NODE ) { Element element = ( Element ) node; Paragraph paragraph = new Paragraph ( element. getTextContent ( ) ) . setTextAlignment ( TextAlignment . CENTER ) ; pdfDoc. add ( paragraph) ; } NodeList children = node. getChildNodes ( ) ; for ( int i = 0 ; i < children. getLength ( ) ; i++ ) { processNode ( pdfDoc, children. item ( i) ) ; } }
}