I'm trying to generate a large amount of pages into a PDF. Here's my code :
private async void Button_Click(object sender, RoutedEventArgs e)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
PdfDocument doc = new PdfDocument();
doc.EnableMemoryOptimization = true;
for (int i = 0; i < 5000; i++){
await GeneratePDF(doc, i);
Debug.WriteLine("doc " + i.ToString());
}
using (MemoryStream stream = new MemoryStream()){
await doc.SaveAsync(stream);
doc.Close(true);
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Debug.WriteLine("generation in " + elapsedMs.ToString() + "ms");
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile stFile = await local.CreateFileAsync("test.pdf", CreationCollisionOption.ReplaceExisting);
using (Windows.Storage.Streams.IRandomAccessStream fileStream = await stFile.OpenAsync(FileAccessMode.ReadWrite)){
using (Stream st = fileStream.AsStreamForWrite()){
st.SetLength(0);
st.Write((stream as MemoryStream).ToArray(), 0, (int)stream.Length);
st.Flush();
}
}
stream.Flush();
}
}
public async Task GeneratePDF(PdfDocument doc,int index)
{
PdfPage page = doc.Pages.Add();
PdfGraphics g = page.Graphics;
PdfBrush brush = new PdfSolidBrush(System.Drawing.Color.FromArgb(255, 0, 0, 0));
PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 36);
for(int i = 0;i < 1000; i++){
g.DrawString("Hello world!", font, brush, new PointF(20, 20+i));
}
}