Tchaps Tchaps - 1 year ago 273
C# Question

XMLWorkerHelper convert html page into pdf produces only first 2 pages

I'm getting only the first two page. I have a generated list of elements in the third page. When there are too many elements in my collection, all pages from there become blank in my pdf output

using (FileStream fs = new FileStream(filePath, FileMode.Create))
Document document = new Document(PageSize.A4, 25, 25, 30, 30);
WebClient wc = new WebClient();
string htmlText = wc.DownloadString(textUrl);

PdfWriter pdfWriter = PdfWriter.GetInstance(document, fs);
// register all fonts in current computer
XMLWorkerFontProvider fontProvider = new XMLWorkerFontProvider();
using (var msHtml = new MemoryStream(System.Text.Encoding.Default.GetBytes(htmlText)))
//Set factories
var cssAppliers = new CssAppliersImpl(fontProvider);
var htmlContext = new HtmlPipelineContext(cssAppliers);

//HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);

string gishaTff = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "GISHA.TTF");

var worker = XMLWorkerHelper.GetInstance();
var cssStream = new FileStream(FolderMapPath("/css/style.css"), FileMode.Open);

worker.ParseXHtml(pdfWriter, document, msHtml, cssStream, new UnicodeFontFactory());

// Close the document

// Close the writer instance

Here is my cshtml code

Answer Source

Here is how i solved my problem. The problem wasn't with the C# backend code. It's seems like the XMLWorkerHelper at the moment doesn't deal well with loop in view. I had to display list of items in my PDF file. The result was well if the collection contains no so many items, But the page break at the level when the the collection contains more than 50 items because this could not be display in a single page. What i did is that i started to count the number of items and at some number like 40, i just include a break element <li style="list-style:none; list-style-type:none; page-break-before:always">@item</li>. And reset the counter and continue display my items. And it was great and my problem was resolved. May be this can be helpful for someone.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download