Hi. I’m converting about 15 pages to PDF using this code and it consistently averages over 30 seconds to run for this block of code, using StopWatch() to measure.
The image I’m adding is about 16KB and is only on the first page. If I take out the image and the pagination, the performance improves somewhat. What am I doing wrong? Thank you.
byte[] pdfBytes;
using (var ms = new MemoryStream())
{
var pdfDocument = new Document();
var htmlFragment = new HtmlFragment(myHtmlString);
pdfDocument.Pages.Add().Paragraphs.Add(htmlFragment);
pdfDocument.PageInfo.Margin = new MarginInfo(36, 45, 36, 36);
pdfDocument.ProcessParagraphs();
var pageNumberStamp = new PageNumberStamp();
pageNumberStamp.Background = false;
pageNumberStamp.Format = $"Page # of {pdfDocument.Pages.Count}";
pageNumberStamp.BottomMargin = 30;
pageNumberStamp.HorizontalAlignment = HorizontalAlignment.Center;
pageNumberStamp.StartingNumber = 1;
pageNumberStamp.TextState.Font = FontRepository.FindFont("Arial");
pageNumberStamp.TextState.FontSize = 10.0F;
pageNumberStamp.TextState.BackgroundColor = Color.LightGray;
// Add page number to each page.
foreach (var page in pdfDocument.Pages)
{
page.AddStamp(pageNumberStamp);
}
// Optimize pdf.
var optimizationOptions = new OptimizationOptions();
optimizationOptions.LinkDuplcateStreams = true;
optimizationOptions.RemoveUnusedObjects = true;
optimizationOptions.RemoveUnusedStreams = true;
optimizationOptions.ImageCompressionOptions.CompressImages = true;
optimizationOptions.ImageCompressionOptions.ImageQuality = 10;
// Optimize the file size by removing unused objects.
pdfDocument.OptimizeResources(optimizationOptions);
var basePath = HttpContext.Current.Server.MapPath("~");
var path = Path.Combine(basePath, @"Content\images\someImage.jpg");
var mender = new PdfFileMend(pdfDocument);
mender.AddImage(path, 1, 37, 600, 109, 895);
mender.Save(ms);
mender.Close();
pdfDocument.Dispose();
// Convert memory stream to byte array.
pdfBytes = ms.ToArray();
}