【发布时间】:2019-02-15 14:29:50
【问题描述】:
我正在尝试使用 ITextSharp 从 HTML 字符串生成 PDF。但是外观样式没有得到应用。我在 stackoverflow 上查看了与它相关的帖子,但没有从他们那里得到任何帮助。 请帮助我如何将 pdf 中的 HTML 转换为 HTML UI 中显示的实际样式。 CSS 包含在样式标签中。 这是我的 C# 代码
public static string GeneratePDF(string html, string cssText="")
{
try
{
// var cssText = "";
Guid random_guid;
random_guid = Guid.NewGuid();
string fileName = random_guid.ToString() + ".pdf";
string filename_with_folder = @"Temp\" + fileName;
string fullFilePath = System.IO.Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, filename_with_folder);
using (var memoryStream = new MemoryStream())
{
var doc = new Document();
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(fullFilePath, FileMode.Create));
doc.Open();
using (var cssMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(cssText)))
{
using (var htmlMemoryStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(html)))
{
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, htmlMemoryStream, cssMemoryStream);
}
}
doc.Close();
fileName = Utility.UploadFileToAzure(fullFilePath, fileName, "application/pdf ");
return fileName;
}
}
catch (Exception ex)
{
ExceptionHandler.LogError(ex);
}
return string.Empty;
}
这是带有 HTMl 字符串和 css 的代码
public void test()
{
StringBuilder sb = new StringBuilder();
StringBuilder css = new StringBuilder();
css.Append(@"<style type='text/css'>
body{font-family: Segoe, 'Segoe UI', 'DejaVu Sans', 'Trebuchet MS', Verdana, 'sans-serif'; background: #f2f2f2; margin: 0; padding: 0; font-size: 20px; color: #565656;}
.outerpdfboxCont{width: 100%; background: #fff; margin: 0 auto; padding: 15px 30px; max-width: 80%; display: table;box-shadow: 1px 1px 2px #ddd;}
.blueBorderLine{background: #0A82B4; height: 10px; width: 100%; margin: 10px auto;}
.workingWrapperboxPdf{margin: 10px 0; padding: 10px 0px; display: table;width: 100%; }
.workingWrapperboxPdf h2{font-size: 36px; font-weight: 500; margin: 40px 0 0; line-height: 40px; color: #000;}
.workingWrapperboxPdf h3{font-size: 18px; font-weight: 300;line-height: 20px;}
.darkB{color: #000!important; font-weight: 500!important;}
.DataboxH{margin: 20px 0; display: table;width: 100%;}
.border-heading{border-bottom: 1px solid #ddd; font-size: 30px!important; line-height: 35px!important; color: #000!important;width: 100%; padding-bottom: 10px;}
</style>");
sb.Append(@"<body>
<div class='outerpdfboxCont'>
<div class='blueBorderLine'></div>
<div class='workingWrapperboxPdf'>
<h3>Dalvir Singh</h3>
<h3 class='darkB'>India</h3>
<div class='DataboxH'>
<h2>Summery Of the PDF</h2>
<h3 class='darkB'>Summery of pdf will go here</h3>
<h3>PDF created on 2018-6-12</h3>
</div>
</div>
</div>
</body>");
GeneratePDF(sb.ToString(),css.ToString());
}
【问题讨论】:
标签: c# itext pdf-generation xmlworker