xml导出pdf简单实现

1. 引入依赖

java 复制代码
<dependency>
   <groupId>com.itextpdf</groupId>
   <artifactId>itext7-core</artifactId>
   <version>8.0.1</version>
</dependency>

2. 代码实现

java 复制代码
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));
        }
    }
}
相关推荐
weixin-a1530030831621 分钟前
【playwright篇】教程(十七)[html元素知识]
java·前端·html
DCTANT44 分钟前
【原创】国产化适配-全量迁移MySQL数据到OpenGauss数据库
java·数据库·spring boot·mysql·opengauss
Touper.1 小时前
SpringBoot -- 自动配置原理
java·spring boot·后端
黄雪超1 小时前
JVM——函数式语法糖:如何使用Function、Stream来编写函数式程序?
java·开发语言·jvm
ThetaarSofVenice1 小时前
对象的finalization机制Test
java·开发语言·jvm
望获linux3 小时前
【实时Linux实战系列】CPU 隔离与屏蔽技术
java·linux·运维·服务器·操作系统·开源软件·嵌入式软件
JosieBook3 小时前
【Java编程动手学】使用IDEA创建第一个HelloJava程序
java·开发语言·intellij-idea
Thomas_YXQ3 小时前
Unity3D DOTS场景流式加载技术
java·开发语言·unity
summer夏1233 小时前
2025.07 做什么
java·android studio
钢铁男儿3 小时前
C# 委托(调用带引用参数的委托)
java·mysql·c#