xml导出pdf简单实现

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 {
        // 读取XML文件
        File xmlFile = new File("example.xml");
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(xmlFile);
        doc.getDocumentElement().normalize();

        // 创建PDF文档
        PdfWriter writer = new PdfWriter("output.pdf");
        PdfDocument pdf = new PdfDocument(writer);
        Document pdfDoc = new Document(pdf, PageSize.A4);

        // 遍历XML元素并将其添加到PDF文档中
        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));
        }
    }
}

你可能感兴趣的:(pdf,xml,java)