HTML 转 PDF

发布于:2024-11-29 ⋅ 阅读:(8) ⋅ 点赞:(0)

dependencies

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>html2pdf</artifactId>
            <version>5.0.5</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>kernel</artifactId>
            <version>8.0.5</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>io</artifactId>
            <version>8.0.5</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>layout</artifactId>
            <version>8.0.5</version>
        </dependency>

代码实现

    @Test
    void htmlToPdf() {
        // IO
        File htmlSource = new File("D:\\test.html");
        File pdfDest = new File("D:\\test.pdf");
        
        try {
            // pdfHTML specific code
            ConverterProperties converterProperties = new ConverterProperties();
            HtmlConverter.convertToPdf(new FileInputStream(htmlSource),new FileOutputStream(pdfDest), converterProperties);
        } catch (IOException e) {
            log.error("生成文件失败", e);
        }
    }
    
    @Test
    void createPdf() {
        
        String dest = "D:\\hello_world.pdf";
        
        //生成文件
        try {
            // 1、创建一个PdfWriter对象,将文档写入到文件中
            PdfWriter writer = new PdfWriter(dest);
            // 2、初始化一个PdfDocument对象
            PdfDocument pdf = new PdfDocument(writer);
            // 3、初始化一个Document对象
            Document document = new Document(pdf);
            // 4、向文档中添加内容
            document.add(new Paragraph("Hello World!"));
            // 5、关闭文档
            document.close();
        } catch (IOException e) {
            log.error("生成文件失败", e);
        }
    }

参考

🐙iTextPdf学习笔记 - Java小白的搬砖路 - 博客园

官方教程:

Convert HTML & CSS to rich, smart PDF documents - iText

iText: Converting HTML to PDF with pdfHTML