im trying to generate multiple pdfs in a Parallel.ForEach.
A single pdf takes 6 sec to generate and return to client, two takes 10 sec, three 15 sec, rest remains linear.
Im using FreeSpire.PDF 6.2.0 from nuget.
The api running in azure app service S1, x64. If i scale up for faster plan, the issue remains (3 sec for single, +2 sec each after).
The relevant code:
- Code: Select all
ConcurrentBag<ReservationDTO> myBag = new ConcurrentBag<ReservationDTO>(returnList);
Parallel.ForEach(myBag, item => {if(item.TicketDTO != null) item.TicketDTO.TicketPdf = GetTicketHTMLAsync(item.TicketDTO.TicketHtml); });
return myBag.ToList();
- Code: Select all
private byte[] GetTicketHTMLAsync(string pdfHtml)
{
if (string.IsNullOrEmpty(pdfHtml)) return null; //not 404, for other services to use the result either way
PdfDocument doc = new PdfDocument();
//PdfPageSettings setting = new PdfPageSettings();
doc.PageSettings.SetMargins(0, 0, 0, 0);
doc.Form.ReadOnly = true;
byte[] byteArray = Encoding.Unicode.GetBytes(Utf8ToUnicode(pdfHtml));
using (var pdfMemoryStream = new MemoryStream())
{
HtmlConverter.Convert(pdfHtml, pdfMemoryStream, LoadHtmlType.SourceCode);
doc.LoadFromStream(pdfMemoryStream);
doc.PageSettings.Size = PdfPageSize.A5;
doc.PageSettings.SetMargins(0, 0, 0, 0);
using (var returnStream = new MemoryStream())
{
doc.SaveToStream(returnStream, FileFormat.PDF);
return returnStream.ToArray();
}
}
}
- Code: Select all
public string Utf8ToUnicode(string utf8String)
{
byte[] utf8Bytes = new byte[utf8String.Length];
for (int i = 0; i < utf8String.Length; ++i)
{
utf8Bytes[i] = (byte)utf8String[i];
}
return Encoding.UTF8.GetString(utf8Bytes, 0, utf8Bytes.Length);
}
Thanks,
Andris