我的 HTML 如下:
<html>
<head>
<title></title>
</head>
<body>
<p>Name:{Applicant Name}</p>
<p>Age:{Applicant Age}</p>
</body>
</html>
可以看出,{Applicant Name} 和 {Applicant Age} 是占位符。
目标是在运行时替换这些占位符值并使用 iTextSharp 生成 PDF。
我能够从 HTML 模板生成 PDF,但无法在运行时替换占位符值。
这是我迄今为止尝试过的:
public void HTML2PDFTest()
{
var name = "some name";
var age = 27;
HtmlConverter.ConvertToPdf
(
new FileInfo(@"D:\test.html")
,new FileInfo(@"D:\test.pdf")
);
}
最终输出将是:
最佳答案
在 iTextSharp 打开并转换 HTML 文件之前,您可以对 HTML 文件执行 String.Replace() 以将占位符更改为所需的值。请参阅下面的示例:
public void HTML2PDFTest()
{
var name = "some name";
var age = 27;
string htmlFileContent = "";
using (System.IO.StreamReader file = new System.IO.StreamReader(@"D:\test.html"))
htmlFileContent = file.ReadToEnd();
htmlFileContent = htmlFileContent.Replace("{Applicant Name}", name).Replace("{Applicant Age}", age.ToString());
using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"D:\test.html"))
file.Write(htmlFileContent);
HtmlConverter.ConvertToPdf
(
new FileInfo(@"D:\test.html"),
new FileInfo(@"D:\test.pdf")
);
}
关于c# - 如何在运行时替换 HTML 的占位符值并使用 iTextSharp 生成 PDF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64916236/