Reputation: 31
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.
Upvotes: 2
Views: 10611
Reputation: 1719
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();
Upvotes: 2