使用itextpdf5.x将网页转为PDF,并添页眉页脚页码

一、用到的Maven依赖

XML 复制代码
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13.3</version>
        </dependency>

        <!-- 中文字体支持 -->
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf.tool</groupId>
            <artifactId>xmlworker</artifactId>
            <version>5.5.13</version>
        </dependency>

二、直接上代码

java 复制代码
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.tool.xml.XMLWorkerHelper;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class HtmlToPdfWithHeadersFooters {

    public static void main(String[] args) {
       // String htmlFile = "D:\\opt\\upFiles\\temp\\模板测试3页面_17243805153171.html";
         String htmlFile = "D:\\opt\\upFiles\\temp\\模板测试3页面_17243757480651.html";
       // String htmlFile = "D:\\opt\\upFiles\\temp\\模板测试3页面_17242121319999.html";
        String pdfFile = "D:\\htmltopdftest\\pdf0001607.pdf";

        html2pdf(htmlFile, pdfFile);
    }

    public static void html2pdf(String htmlFile, String pdfFile) {
        try (FileOutputStream fos = new FileOutputStream(pdfFile)) {
            Document document = new Document(PageSize.A4, 36, 36, 36, 36); // 设置页边距
            PdfWriter writer = PdfWriter.getInstance(document, fos);
            document.open();

            // 注册页眉和页脚事件处理器
            writer.setPageEvent(new HeadersFootersHandler());
            InputStream inputStream = new FileInputStream(htmlFile);
            // 将 HTML 转换成 PDF
            XMLWorkerHelper.getInstance().parseXHtml(writer, document, inputStream);
            document.close();
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
    }

    static class HeadersFootersHandler extends PdfPageEventHelper {

        BaseFont baseFont;
        Font font ;

        {
            try {
                baseFont = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
                font = new Font(baseFont, 8, Font.NORMAL);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onEndPage(PdfWriter writer, Document document) {
            PdfPTable table = new PdfPTable(1);
            table.setTotalWidth(document.right() - document.left());
            float pageWidth = document.right() - document.left();
            pageWidth = (pageWidth - 36)/2;
            table.setWidthPercentage(99);
            table.getDefaultCell().setBorder(2);
            table.getDefaultCell().setPadding(3);

            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);

            // 添加页眉
            PdfPCell headerCell = new PdfPCell(new Paragraph("页眉:中国 ", font));
            headerCell.setBorder(0);
            headerCell.setPaddingBottom(0);
            table.addCell(headerCell);

            PdfPCell footerCell = new PdfPCell(new Paragraph("页码 " + writer.getPageNumber(), font));
            footerCell.setBorder(0);
            footerCell.setPaddingTop(10);
            table.addCell(footerCell);

            // 将页眉页脚添加到文档中
            float yHeader = document.top() + 20; // 页眉距离顶部的距离
            table.writeSelectedRows(0, -1, pageWidth, yHeader, writer.getDirectContent());
        }


    }
}

三、测试用的HTML文件

注意,HTML文件的内容必须严格遵守XHTML规范,否则会抛异常。

不知道怎么上传附件,我直接粘贴HTML的代码

html 复制代码
<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta><style type="text/css">body { font-family:arial,helvetica,sans-serif; font-size:16px }p {margin:3px; line-height:24px;} .mce-item-table[border="0"],.mce-item-table[border="0"] td{border: 0px dashed #bbb;}</style></head><body><html>
 <head></head>
 <body>
  <p><span id="billNum" class="mceNonEditable blmField" contenteditable="false">xxx</span></p>
  <p><span id="billBuildTime" class="mceNonEditable blmField" contenteditable="false">xxx</span></p>
  <p><span style="font-size: 48px; color: rgb(45, 194, 107);" data-mce-style="font-size: 48px; color: #2dc26b;">today&nbsp; &nbsp;is a good day!</span></p>
  <p><span style="font-size: 48px; color: rgb(45, 194, 107);" data-mce-style="font-size: 48px; color: #2dc26b;"><img src="http://192.168.105.151:7800/bsblm/sys/common/static/jeditor/icon_1724213898321.jpg" alt="" data-mce-src="http://192.168.105.151:7800/bsblm/sys/common/static/jeditor/icon_1724213898321.jpg" width="235" height="235"></img><br data-mce-bogus="1"></br></span></p>
  <p class="blm_template_break" style="page-break-before: always; margin: 0; padding: 0; text-align: center; color: #666;" contenteditable="false" data-mce-style="page-break-before: always; margin: 0; padding: 0; text-align: center; color: #666;"></p>
  <p>&nbsp;<span id="billStageType" class="mceNonEditable blmField" contenteditable="false">xxx</span></p>
  <p><span id="billSendTime" class="mceNonEditable blmField" contenteditable="false">xxx</span></p>
  <p><span style="font-size: 36px; font-family: SimSun, serif;" data-mce-style="font-size: 36px; font-family: SimSun, serif;"><strong><span style="color: rgb(230, 126, 35);" data-mce-style="color: #e67e23;">Happy BirthDay!</span></strong></span></p>
  <table style="border-collapse: collapse; width: 100%;" border="1">
   <colgroup>
    <col style="width: 20.0255%;"></col>
    <col style="width: 20.0255%;"></col>
    <col style="width: 20.0255%;"></col>
    <col style="width: 20.0255%;"></col>
    <col style="width: 20.0255%;"></col>
   </colgroup>
   <tbody>
    <tr>
     <td><span style="color: rgb(224, 62, 45);" data-mce-style="color: #e03e2d;">great!</span></td>
     <td><br></br></td>
     <td><br></br></td>
     <td><br></br></td>
     <td><br></br></td>
    </tr>
    <tr>
     <td><br></br></td>
     <td><span style="font-size: 24px; color: rgb(230, 126, 35);" data-mce-style="font-size: 24px; color: #e67e23;"><strong>good!</strong></span></td>
     <td><br></br></td>
     <td><br></br></td>
     <td><br></br></td>
    </tr>
    <tr>
     <td><br></br></td>
     <td><br></br></td>
     <td><br></br></td>
     <td><span style="font-size: 36px; color: rgb(224, 62, 45);" data-mce-style="font-size: 36px; color: #e03e2d;"><strong>Yes!</strong></span></td>
     <td><br></br></td>
    </tr>
   </tbody>
  </table>
  <p class="blm_template_break" style="page-break-before: always; margin: 0; padding: 0; text-align: center; color: #666;" contenteditable="false" data-mce-style="page-break-before: always; margin: 0; padding: 0; text-align: center; color: #666;"></p>
  <p>&nbsp;<span id="payForReason" class="mceNonEditable blmField" contenteditable="false">xxx</span></p>
  <p><span id="payForReason" class="mceNonEditable blmField" contenteditable="false">xxx</span></p>
  <p><span style="font-size: 36px; color: rgb(224, 62, 45);" data-mce-style="font-size: 36px; color: #e03e2d;">Thank you!</span></p>
  <p><br data-mce-bogus="1"></br></p>
  <p><br data-mce-bogus="1"></br></p>
  <p><br data-mce-bogus="1"></br></p>
 </body>
</html></body></html>

四、网页转PDF的效果

结果为三张PDF,不知道怎么上传附件,我直接上截图看看效果。

相关推荐
记得开心一点嘛6 分钟前
Nginx与Tomcat之间的关系
java·nginx·tomcat
虾稿18 分钟前
[手机Linux] 七,NextCloud优化设置
linux·运维·服务器
界面开发小八哥18 分钟前
「Java EE开发指南」如何用MyEclipse构建一个Web项目?(一)
java·前端·ide·java-ee·myeclipse
王伯爵21 分钟前
<packaging>jar</packaging>和<packaging>pom</packaging>的区别
java·pycharm·jar
稳重的大王25 分钟前
威联通NAS部署openwrt软路由保姆级教程附镜像文件
运维·服务器
ZHOUPUYU31 分钟前
VMware虚拟机超详细安装Linux教程(最新版)
linux·运维·服务器·windows·微软·centos·虚拟机
成都渲染101云渲染666638 分钟前
云渲染,Enscape、D5、Lumion渲染提速教程
运维·服务器·unity·电脑·图形渲染·blender·houdini
Eiceblue39 分钟前
使用Python获取PDF文本和图片的精确位置
开发语言·python·pdf
初级代码游戏42 分钟前
关于linux的ld.so.conf.d
linux·运维·服务器
我叫czc42 分钟前
【Python高级353】python实现多线程版本的TCP服务器
服务器·python·tcp/ip