使用 iText 7 将 HTML 模板转换为 PDF:如何移动跨页面打印的表格

如何解决使用 iText 7 将 HTML 模板转换为 PDF:如何移动跨页面打印的表格

我正在开发一个 asp.net mvc 项目,我正在使用一个 html 模板来生成一个带有动态数据的发票文档,由于车把,我填写了这些数据。生成的 html 正在使用 iText 7 转换为 PDF,因为这是公司需要使用的工具,但是由于显示数据的 html 表,我在将其转换为 PDF 时遇到了问题,有时有足够的数据可以放在一页中,但在其他情况下,有许多行会遇到分页符,跨两页打印数据。每当数据不适合一页时,我需要将整个表格块移动到下一页。

这是模板(Mytemplate.html):

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <style type="text/css">
        <!-- Removed inline styles for space reasons -->
    </style>
</head>
<body>
<div style="width: 100%; margin: 0 auto; text-align: center; display: flex; justify-content: center;">
    <div style="max-width: 700px; background-color: white; width: 100%">
        <table style="width:100%">
            <tbody>
            <tr>
                <td>
                    <table class="table-header table-information m-0 border-zero">
                        <tr>
                            <td class="text-al" style="vertical-align: top">
                                <img src="{{baseUrl}}\images\clear_purple.png" style="width: 150px; height: 50px;">
                            </td>
                            <td class="text-al" style="vertical-align: top">
                                <table class="table-information m-0 border-zero">
                                    <tbody>
                                        <tr>
                                            <td class="td-information p-0">
                                                <p class="text p-0">Insured: {{insured}}</p>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td class="td-information p-0">
                                                <p class="text p-0">{{facilityName}}</p>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </td>
                            <td class="text-al vertical-ab">
                                <table class="table-information m-0 border-zero">
                                    <tbody>
                                        <tr>
                                            <td class="td-information p-0">
                                                <p class="text p-0">Invoice Period: {{invoicePeriod}}</p>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td class="td-information p-0">
                                                <p class="text p-0">Date sent to LCTI: {{invoiceDateLTCI}}</p>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td class="td-information p-0">
                                                <p class="text p-0">LTCI Rep: {{clientReferrer}}</p>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
            <tr>
                <td>
                    <table class="table-information">
                        <tbody>
                        <tr class="tr-information">
                            <th class="td-background" colspan="3">
                                <p class="text-title">Residency Information</p>
                            </th>
                        </tr>
                        <tr>
                            <td class="td-information p-0 vertical-ab" colspan="3">
                                <table class="table-information border-zero mb-0"">
                                    <tbody>
                                        <tr>
                                            <td class="td-information w-35">
                                                <p class="text text-bold">Facility Type</p>
                                                <p class="text text-bold">Room/Unit Number</p>
                                                <p class="text text-bold">Insurance Provider</p>
                                                <p class="text text-bold">Insured’s Policy Number</p>
                                                <p class="text text-bold">Invoice Number</p>
                                            </td>
                                            <td class="td-information w-65">
                                                <p class="text-light">{{residencyInfo.facilityType}}</p>
                                                <p class="text-light">{{residencyInfo.roomNumberChangeTo}}{{#if residencyInfo.roomNumberChange}} - {{residencyInfo.roomNumberChangeReason}}{{/if}}</p>
                                                <p class="text-light">{{residencyInfo.insurerProvider}}</p>
                                                <p class="text-light">{{residencyInfo.policyNumber}}</p>
                                                <p class="text-light">{{residencyInfo.invoiceNumber}}</p>
                                            </td>
                                        </tr>
                                    </tbody>
                                </table>
                            </td>
                        </tr>
                        <tr>
                            <td class="td-information td-border-top br-1 w-45">
                                <table class="w-full">
                                    <tbody>
                                        {{#if residencyInfo.haveDaysOutOfFacility}}
                                        <tr>
                                            <td>
                                                <p class="text text-bold">Total Days in Facility</p>
                                            </td>
                                            <td>
                                                <p class="text-light">{{residencyInfo.totalDaysInFacility}}</p>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td>
                                                <p class="text text-bold">Total Days out of Facility</p>
                                            </td>
                                            <td>
                                                <p class="text-light">{{residencyInfo.totalDaysOutOfFacility}}</p>
                                            </td>
                                        </tr>
                                        {{/if}}
                                        {{#if residencyInfo.haveBedHoldDays}}
                                        <tr>
                                            <td>
                                                <p class="text text-bold">Bedhold Days</p>
                                            </td>
                                            <td>
                                                <p class="text-light">{{residencyInfo.bedHoldDays}}</p>
                                            </td>
                                        </tr>
                                        {{/if}}
                                    </tbody>
                                </table>
                            </td>
                            <td class="td-information bl td-border-top">
                                <table class="w-full">
                                    <tbody>
                                        <tr>
                                            <td class="td-information-width">
                                                <p class="text-light-2">Reason for Absence</p>
                                            </td>
                                            <td class="td-information-width">
                                                <p class="text-light-2 text-ar">Dates of Absence</p>
                                            </td>
                                        </tr>
                                        {{#each residencyInfo.absenceReasons}}
                                        <tr>
                                            <td>
                                                <p class="text-light">{{reason}}</p>
                                            </td>
                                            <td>
                                                <p class="text-light text-ar">{{from}}th{{#if hasTo}} - {{to}}th{{/if}}</p>
                                            </td>
                                        </tr>
                                        {{/each}}
                                    </tbody>
                                </table>
                            </td>
                        </tr>
                        </tbody>
                    </table>
                </td>
            </tr>
            <tr>
                <td>
                    <table class="table-information">
                        <tbody>
                            <tr class="tr-information">
                                <th class="td-background" colspan="3">
                                    <p class="text-title">Care Provided</p>
                                </th>
                            </tr>
                            <tr>
                                <td class="td-information p-0" style="width: 50%;">
                                    <table class="table-information border-zero mb-0">
                                        <tbody>
                                            <tr>
                                                <th class="td-information w-58 th-activity td-border-bottom">
                                                    <p class="text text-bold">Activities of Daily Living (ADLS)</p>
                                                </th>
                                                <th class="td-information p-0 w-14 td-border-bottom vertical-ab">
                                                    <div class="rotate-315">
                                                        <p class="text-s10 text-ac text-gray-500">Standby</p>
                                                    </div>
                                                </th>
                                                <th class="td-information p-0 w-14 td-border-bottom vertical-ab">
                                                    <div class="rotate-315">
                                                        <p class="text-s10 text-ac text-gray-500">Hands On</p>
                                                    </div>
                                                </th>
                                                <th class="td-information p-0 w-14 td-border-bottom vertical-ab">
                                                    <div class="rotate-315">
                                                        <p class="text-s10 text-ac text-gray-500">Provided</p>
                                                    </div>
                                                </th>
                                            </tr>

                                            {{#each careProvided.adls}}
                                            <tr>
                                                <td class="td-information th-activity br-1 vertical-ac td-border-bottom">
                                                    <p class="text text-light">{{name}}</p>
                                                </td>
                                                <td class="td-information p-4 br-1 text-ac vertical-ac td-border-bottom">
                                                    {{#if standBy}}
                                                    <img src="{{../baseUrl}}\images\clear_check.png" style="width: 14px; height: 14px;">
                                                    {{/if}}
                                                </td>
                                                <td class="td-information p-4 br-1 text-ac vertical-ac td-border-bottom">
                                                    {{#if handsOn}}
                                                    <img src="{{../baseUrl}}\images\clear_check.png" style="width: 14px; height: 14px;">
                                                    {{/if}}
                                                </td>
                                                <td class="td-information p-4 br-1 text-ac vertical-ac td-border-bottom">
                                                    {{#if provided}}
                                                    <img src="{{../baseUrl}}\images\clear_check.png" style="width: 14px; height: 14px;">
                                                    {{/if}}
                                                </td>
                                            </tr>
                                            {{/each}}
                                        </tbody>
                                    </table>
                                </td>
                                <td class="td-information p-0" rowspan="3" style="width: 50%; padding-top: 7px;">
                                    <table class="table-information m-0 border-zero mb-0">
                                        <tbody>
                                            <tr>
                                                <th class="td-information td-border-bottom">
                                                    <p class="text text-bold pl-10">Instrumental Activities of Daily Living (IADLS)</p>
                                                </th>
                                            </tr>
                                            {{#each careProvided.iadls}}
                                            <tr>
                                                <td class="td-information pt-0 pb-0">
                                                    <p class="text text-light pl-10 ">{{name}}</p>
                                                </td>
                                            </tr>
                                            {{/each}}
                                        </tbody>
                                    </table>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </td>
            </tr>
            <tr>
                <td>
                    <table class="table-information">
                        <tbody>
                            <tr class="tr-information">
                                <th class="td-background" colspan="4">
                                    <p class="text-title">Invoice Totals</p>
                                </th>
                            </tr>
                            <tr>
                                <td style="width: 58%;">
                                    <table class="table-information border-zero m-0">
                                        <tbody>
                                            {{#each invoiceTotals.charges}}
                                            <tr>
                                                <td class="td-information pt-0-10" style="width:60%">
                                                    <p class="text text-bold" style="font-size:15px">{{name}}</p>
                                                </td>
                                                <td class="td-information pt-0-10" style="width:15%">
                                                    <p class="text text-light text-ar">{{amount}}</p>
                                                </td>
                                                <td class="td-information p-4" style="width:25%">
                                                    {{#if includedRnB}}
                                                    <p class="text-small">Included in R&B</p>
                                                    {{/if}}
                                                </td>
                                            </tr>
                                            {{/each}}
                                            <tr>
                                                <td class="td-information text-ar" style="padding-right: 10px" colspan="2">
                                                    <p class="text-title-35 text-green-500 text-ar">${{invoiceTotals.totalAmount}}</p>
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </td>
                                <td class="td-information pt-0" rowspan="2" style="width: 48%;">
                                    <table class="table-information p-0 m-0 border-zero">
                                        <tbody>
                                            <tr>
                                                <th class="td-information pl-0 pt-0-10"><p class="text text-bold">Other Payment sources:</p></th>
                                            </tr>
                                            {{#each invoiceTotals.otherPaymentSources}}
                                            <tr>
                                                <td class="td-information pl-0 pt-0-10"><p class="text text-light">{{name}}</p></td>
                                            </tr>
                                            {{/each}}
                                        </tbody>
                                    </table>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </td>
            </tr>
            <tr>
                <td>
                    <table class="table-information">
                        <tbody>
                            <tr class="tr-information">
                                <th class="td-background" style="width: 25%">
                                    <p class="text-title text-al" style="font-size: 16px; padding-left: 10px">Reviewed By</p>
                                </th>
                                <th class="td-background" style="width: 35%">
                                    <p class="text-title text-al" style="font-size: 16px; padding-left: 10px">Signed By</p>
                                </th>
                                <th class="td-background" style="width: 25%">
                                    <p class="text-title text-al" style="font-size: 16px; padding-left: 10px">Signed On</p>
                                </th>
                                <th class="td-background" style="width: 15%">
                                    <p class="text-title text-al" style="font-size: 16px; padding-left: 10px">Ip Address</p>
                                </th>
                            </tr>
                            <tr>
                                <td class="td-information pt-0-10" style="padding-top: 16px;"><p class="text pl-4" style="font-size: 15px">{{signature.facility.title}}</p></td>
                                <td class="td-information pt-0-10" style="padding-top: 16px;"><p class="text" style="font-family: BrushScript; font-size: 24px">{{signature.facility.signedBy}}</p></td>
                                <td class="td-information pt-0-10" style="padding-top: 16px;"><p class="text" style="font-size: 15px">{{signature.facility.signedOn}}</p></td>
                                <td class="td-information pt-0-10" style="padding-top: 16px;"><p class="text text-light" style="font-size: 15px">{{signature.facility.ipAddress}}</p></td>
                            </tr>
                            <tr>
                                <td class="td-information pt-0-10"><p class="text pl-4" style="font-size: 15px">{{signature.client.title}}</p></td>
                                <td class="td-information pt-0-10"><p class="text" style="font-size: 15px">{{signature.client.signedBy}}</p></td>
                                <td class="td-information pt-0-10"><p class="text" style="font-size: 15px">{{signature.client.signedOn}}</p></td>
                                <td class="td-information pt-0-10"><p class="text text-light" style="font-size: 15px">{{signature.client.ipAddress}}</p></td>
                            </tr>
                            <tr>
                                <td class="td-information pt-0-10"><p class="text pl-4" style="font-size: 15px">{{signature.local.title}}</p></td>
                                <td class="td-information pt-0-10"><p class="text" style="font-size: 15px">{{signature.local.signedBy}}</p></td>
                                <td class="td-information pt-0-10"><p class="text" style="font-size: 15px">{{signature.local.signedOn}}</p></td>
                                <td class="td-information pt-0-10"><p class="text text-light" style="font-size: 15px">{{signature.local.ipAddress}}</p></td>
                            </tr>
                        </tbody>
                    </table>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</div>
</body>
</html>

您可以看到诸如{{insured}}等标记和用于循环数据的{{#each ResidencesInfo.absenceReasons}}等命令,所有这些都是handlebars需要的数据替换。部分代码如下:

string templateHtml = File.ReadAllText(System.IO.Path.Combine(basePath,"templates/MyTemplate.html"));
var template = Handlebars.Compile(templateHtml);
var data = new
{
    baseUrl = basePath,insured = invoice.CustomerStatus,// Customer Name
    facilityName = invoice.FacilityName,invoicePeriod = invoice.PeriodFrom.ToString("MMM yyyy"),invoiceDateLTCI = DateTime.Now.ToString("MM/dd/yyyy"),clientReferrer = invoice.ClientReferrerName,residencyInfo = new
    {
        facilityType = currenttFacilityType,insurerProvider = invoice.Insurer,policyNumber = invoice.ClaimNumber,... // removed intencionally
        absenceReasons = JsonConvert.DeserializeAnonymousType(JsonConvert.SerializeObject(facilityAbsenceReasons),jsonFacilityAbsenceReasonsDefinition)
    },careProvided = new
    {
        adls = ...,// removed intencionally
        iadls = ... // removed intencionally
    },invoiceTotals = new
    {
        charges = JsonConvert.DeserializeAnonymousType(JsonConvert.SerializeObject(facilityCharges),jsonFacilityChargesDefinition),totalAmount = totalAmount,otherPaymentSources = JsonConvert.DeserializeAnonymousType(JsonConvert.SerializeObject(facilityOtherPayments),jsonFacilityOtherPaymentsDefinition)
    },signature = new
    {
        facility = new
        {
            signedBy = invoice.SignatureName,signedOn = DateTime.ParseExact(invoice.SignatureDate,"M/d/yyyy h:mm:ss tt",CultureInfo.InvariantCulture).ToString("MM/dd/yyyy h:mm tt"),title = invoice.SignatureFacilityTitleName,ipAddress = invoice.IpAddress
        },client = new
        {
            ... // removed intencionally
        },...
    }
};

string invoiceHtml = template(data);

invoiceHtml 具有带数据的最终 HTML,用于通过 iText7 生成 PDF。部分代码如下:

ConverterProperties converterProperties = new ConverterProperties();

// Create a Temp PDF file temporary,remove this when the whole invoice is created to manaqge it as stream byte[]
string file = System.IO.Path.Combine(basePath,$@"Documents\Temp_Invoice_{invoice.FacilityInvoiceId}.pdf");

PdfWriter writer = new PdfWriter(file);
PdfDocument pdf = new PdfDocument(writer);
pdf.SetDefaultPageSize(PageSize.LEGAL);
var document = HtmlConverter.ConvertToDocument(invoiceHtml,pdf,converterProperties);
document.Close();

这是 PDF 文档,您可以在其中查看跨分页符打印的签名者部分。在这种情况下,如果在上述部分(收费)中打印的数据太多,无法以这种方式生成签名者部分的打印,我需要将签名者块移动到新页面。甚至,如果费用部分(发票总计)太多,也无法放入第一页,我需要将其移至下一页。截图如下:

enter image description here

我尝试使用 ConverToElements 恢复 IElements,但它给了我整个元素对象,而这些对象不属于任何页面。

感谢您的帮助。

解决方法

CSS 属性 page-break-inside 由 iText 7 的 HTML 到 PDF 转换处理,以避免在元素内分页。在不想分成两页的表格上:

<table style="page-break-inside: avoid;">
<!-- table content -->
</table>

当然,如果表格长到比页面还大的高度,就难免要拆分了。

或者,当首先使用 ConvertToElements 转换为 Elements 时,您可以在生成的 SetKeepTogether(true) 实例上使用 Table

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res