Is it possible to Save multiple parallel pdfs in .Net using parallel programming


#1

Hello Aspose,

I’m running into a performance issue while generating a pdf which has more data in it. According to my observations it is taking more time in saving the pdf document into the memorystream.

In order to over come this issue, I’m trying to use parallel programming in C# to divide the final pdf into few chunks of individual pdfs and concatenate them into one complete final pdf.

FinalPdf = [chunk1, chunk2, chunk3, chunk4]

Now, trying to use parallel programming to generate all individual chunks of pdf parallely.
Then finally I’m concatinating them into one finalPdf.

List<byte[]> finalPdfList= new List<byte[]>();

SetLicense(); // Setting the license

Parallel.ForEach(FinalPdf , async (chunk) => {
byte[] pdfData = CreateAndSavePdfChunk(chunk);
finalPdfList.Add(pdfData);
});

CreateAndSavePdfChunk(chunk)
{
creating tables, pdf pages and generating pdfContext.
return await GetPdfResultsAsync();
}

public async Task<byte[]> GetPdfResultsAsync()
{
return await Task.Run(() =>
{
using (var pdfStream = new MemoryStream())
{
PdfContext.Pdf.Save(pdfStream); // Getting exceptions like System.NullReferenceException or Instance not set
pdfStream.Position = 0;
return pdfStream.ToArray();
}
});
}

I thought Setting license once and calling GetPdfResultsAsync() parallely for each pdf multiple times should solve the problem.
But it is throwing exceptions.

Can we set the license once and save multiple pdfs with that licese right?

public void SetLicense()
{
var license = new License();
lock (_licenseLocker)
{
using (var stream = new MemoryStream(ReportsResource.Aspose_Pdf))
{
license.SetLicense(stream);
}
}
}

In our application (using Aspose.pdf version 17.12.0) we want to see the data of 1500 pages in pdf which is taking more time while saving the pdfstream.

What would be the solution for this?


#2

@JaySama588

Thank you for contacting support.

You are using an outdated version of the API so please upgrade to Aspose.PDF for .NET 18.12 which includes more features and bug fixes. Moreover, Aspose.PDF for .NET is multi-thread safe API as long as only one thread works on one document at a time. Likewise, different threads can safely work on different documents at the same time. In other words, multi-threading may help while splitting a PDF document but it can cause anomalies when different documents will be concatenated to one same PDF document.

Furthermore, license needs to be set only once and any number of documents can be generated or manipulated until the application keeps running.