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));
        }
    }
}
相关推荐
chuan.bai10 小时前
Java RAG 实战(第 8 篇):Spring Boot RAG 查询 API
java·spring boot·贪心算法
FlyWIHTSKY10 小时前
idea中集成claude功能
java·ide·人工智能·intellij-idea·cloudera
Java成神之路-10 小时前
Spring AI 统一结构化返回:ChatModel / ChatClient 两种实现方式
java·springaialibaba
Mr. zhihao10 小时前
深度解析:为什么Java序列化需要搭配ByteArrayOutputStream?IO装饰器模式的精妙设计
java·开发语言·装饰器模式
vx-程序开发11 小时前
springboot旅游推介平台---附源码24175
java·spring boot·python·spring cloud·eclipse·django·idea
艾莉丝努力练剑11 小时前
【QT:解决问题】Qt5Core.dll:无法定位程序输入点
java·开发语言·qt·学习·面试
小蒜学长11 小时前
“喵汪联盟”宠物领养系统的设计与实现(代码+数据库+LW)
java·spring boot·后端·宠物
程序员黑豆11 小时前
Java字符串常量池完全指南:原理、intern()方法与性能优化最佳实践
java·前端·ai编程
AI人工智能+电脑小能手11 小时前
大白话说Java设计模式-14-适配器模式(业务实战篇)
java·设计模式·适配器模式·系统兼容·多渠道对接
xbgRS14 小时前
springboot的自动装配
java·spring boot