我正在尝试使用 iTextSharp 将我的网页的一部分转换为 pdf,虽然 pdf 生成工作正常,但没有应用任何 css 样式。我试过一次应用一种样式,但这似乎不起作用。到目前为止,这是我想出的:
//Get the portion of the page to convert.
StringBuilder sb = new StringBuilder();
print_div.RenderControl(new HtmlTextWriter(new StringWriter(sb)));
string html = sb.ToString();
//Generate a random filename to use for the pdf
Guid random_guid;
random_guid = Guid.NewGuid();
string fileName = random_guid.ToString() + ".pdf";
string filename_with_folder = @"pdf\sl_" + fileName;
string fullFilePath = System.IO.Path.Combine(Request.PhysicalApplicationPath, filename_with_folder);
using (Document doc = new Document())
{
// Create the pdf
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(fullFilePath, FileMode.Create));
doc.Open();
try
{
//Set the font size for all elements
StyleSheet styles = new StyleSheet();
styles.LoadStyle("body", "fontsize", "8px");
//Write the content to the pdf document
StringReader sr = new StringReader(html);
XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, sr);
}
catch (Exception ex)
{
}
doc.Close();
}
我错过了什么吗?我开始使用 HTMLWorker 并切换到 XMLWorker,但我想我现在只是让自己感到困惑。帮助将不胜感激。
尝试#2
谢谢回复!这是我想出的,但它不起作用。我的内容现在根本没有出现在 pdf 中,我不知道为什么。有什么想法吗?
using (Document doc = new Document())
{
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(fullFilePath, FileMode.Create));
doc.Open();
// CSS
var cssResolver = new StyleAttrCSSResolver();
var cssFile = XMLWorkerHelper.GetCSS(new FileStream(HttpContext.Current.Server.MapPath("~/css/print.css"), FileMode.Open));
cssResolver.AddCss(cssFile);
// HTML
CssAppliers ca = new CssAppliersImpl();
HtmlPipelineContext hpc = new HtmlPipelineContext(ca);
hpc.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
// PIPELINES
PdfWriterPipeline pdf = new PdfWriterPipeline(doc, writer);
HtmlPipeline htmlPipe = new HtmlPipeline(hpc, pdf);
CssResolverPipeline css = new CssResolverPipeline(cssResolver, htmlPipe);
XMLWorker worker = new XMLWorker(css, true);
XMLParser p = new XMLParser(worker);
StringReader sr = new StringReader(html);
p.Parse(sr);
doc.Close();
}
我接近了,还是我完全错过了重点?