I'm doing a application to work with PDF and TIFF files. To divide them, the user opens the file or folder (if it is a folder, it gets all the files inside) and the app splits the file, getting a tiny image (thumbnail) in JPG format. Then it creates a ListViewItem adding the thumbnail, the name and the size of the file.
But it takes too long (1:40min) with a PDF with 68 pages, so if a larger PDF is opened, it will take too long.
So I wish someone could say where can I improve my code so it doesn't take that long.
CODE
public void SplitPDF2(string input)
{
try
{
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(input);
iTextSharp.text.pdf.PdfReader.unethicalreading = true;
string name = Path.GetFileNameWithoutExtension(input);
for (int i = 1; i <= reader.NumberOfPages; i++)
{
using (MemoryStream ms = new MemoryStream())
{
//get thumbnail from 1st page-----------------------------------------------------
using (var document = PdfiumViewer.PdfDocument.Load(input))
{
var image = document.Render(i - 1, 60, 84, 300, 300, true);
image.Save(ms, ImageFormat.Jpeg);
thumbnails.Images.Add(j.ToString(), image);
image.Dispose();
}
//split pdf-----------------------------------------------------------------------
string p = AppDomain.CurrentDomain.BaseDirectory + "temporario\\" + name + " - Pagina " + i + ".PDF";
using (Stream outputStream = new FileStream(p, FileMode.Create))
{
Document doc = new Document();
PdfWriter pdfWriter = PdfWriter.GetInstance(doc, outputStream);
doc.Open();
PdfContentByte pdfContentByte = pdfWriter.DirectContent;
PdfImportedPage importedpage = pdfWriter.GetImportedPage(reader, i);
iTextSharp.text.Rectangle mediabox = reader.GetPageSize(i);
doc.SetPageSize(mediabox);
doc.NewPage();
pdfContentByte.AddTemplate(importedpage, 0, 0);
doc.Close();
doc.Dispose();
pdfWriter.Dispose();
}
//in the end it will add the thumbnail, the name and the size of the file to the ListView
FileInfo f = new FileInfo(p);
ListViewItem _item1 = new ListViewItem();
_item1.ImageKey = j.ToString(); //image
_item1.SubItems.Add(name + " - Pagina " + i + ".PDF"); //name
_item1.SubItems.Add(f.Length.ToString()); //size
lista2.Items.Add(_item1);
j++;
}
}
reader.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Erro", MessageBoxButtons.OK);
}
}
using
andDispose
at the same time, nousing
in other cases... quite a mess. \$\endgroup\$