C# 如何在运行时替换HTML的占位符值并使用iTextSharp生成PDF?
我的HTML格式如下:C# 如何在运行时替换HTML的占位符值并使用iTextSharp生成PDF?,c#,html,pdf,itext,C#,Html,Pdf,Itext,我的HTML格式如下: <html> <head> <title></title> </head> <body> <p>Name:{Applicant Name}</p> <p>Age:{Applicant Age}</p> <
<html>
<head>
<title></title>
</head>
<body>
<p>Name:{Applicant Name}</p>
<p>Age:{Applicant Age}</p>
</body>
</html>
最终产出将是:
在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")
);
}
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")
);
}