Itext7 HTML to PDF conversion using Html2pdf when HTML is passed as input string and CSS as file

情到浓时终转凉″ 提交于 2019-12-11 08:19:49

问题


I have already implemented the HTML to PDF conversion via Itext 5 XMLWorker. Please find the code below:

using (var ms = new MemoryStream())
using (var document = new Document())
{
 using (var writer = PdfWriter.GetInstance(document, ms))
 {
  document.Open();
  document.SetMargins(30, 60, 60, 60);
  using (var strReader = new StringReader(htmlToExport))
  {
    //Set factories
    var htmlContext = new HtmlPipelineContext(null);
    htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
    //Set css
    var cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver   (false);
    // cssResolver.AddCssFile(HttpContext.Current.Server.MapPath  ("~/Content/bootstrap.min.css"),
    //    true);
    cssResolver.AddCssFile("http://localhost:8902/Content/bootstrap.css", true);
    //Export
    var pipeline = new CssResolverPipeline(cssResolver,
    new HtmlPipeline(htmlContext, new PdfWriterPipeline(document, writer)));
    var worker = new XMLWorker(pipeline, true);
    var xmlParse = new XMLParser(true, worker);
    xmlParse.Parse(strReader);
    xmlParse.Flush();
  }
  document.Close();
  }
}

I am unable to find the relevant example to full fill above requirement in Itext7.


回答1:


You no longer have to pass/add the CSS file explicitly, pdfHTML(Html2Pdf was the internal development name for a while), can pick up stylesheets linked in the HTML. You might optionally have to define a base resource location if your CSS is not located in the same folder as your HTML.

In your HTML, add the following line in the header

<link rel="stylesheet" type="text/css" href="bootstrap.css"/>

And the conversion code of you want to add them to a

File pdf = new File(pdfDest);
pdf.getParentFile().mkdirs();

PdfWriter writer  = new PdfWriter(pdfDest);
PdfDocument pdfDoc = new PdfDocument(writer);

ConverterProperties converterProperties = new ConverterProperties().setBaseUri(resourceLoc);

HtmlConverter.convertToPdf(new FileInputStream(htmlSource), pdfDoc, converterProperties);
pdfDoc.close();


来源:https://stackoverflow.com/questions/44157423/itext7-html-to-pdf-conversion-using-html2pdf-when-html-is-passed-as-input-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!