| PINSystems Source Samples: PDFium | Save Pages To Image Files |
SourceSamples Home |
using (PdfiumViewer.PdfDocument pdfDocument = PdfiumViewer.PdfDocument.Load(<PdfFilePath>))
{
System.Drawing.Image bitmapImage = pdfDocument.Render(0, 200, 200, true);
bitmapImage.Save(<ImageFileName>, System.Drawing.Imaging.ImageFormat.Jpeg);
}
public static List<string> SaveToImages(System.IO.FileInfo SourcePdf, string PageSpecs, string OutputFileBase, PSI.PDF.Procs.IMAGEFORMAT ImgFormat, bool Overwrite)
{
int dpiX = 200;
int dpiY = 200;
int imgHeight;
int imgWidth;
string file;
List<string> savedImages = new List<string>();
IList<System.Drawing.SizeF> pageSizes;
List<int> savePages = null;
ImageFormatSpecs ifs = null;
System.Drawing.Image bitmapImage;
if (SourcePdf == null || !System.IO.File.Exists(SourcePdf.FullName))
throw new ArgumentException("\"SourcePdf\" must be defined and exist");
if (OutputFileBase == null || !System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(OutputFileBase)))
throw new ArgumentException("\"OutputFileBase\" must be defined and the target folder must exist");
if (PageSpecs == null || PageSpecs.Trim().Length == 0)
throw new ArgumentException("\"PageSpecs\" must be defined");
ifs = PSI.PDF.Procs.GetImageFormatSpecs(ImgFormat);
using (PdfiumViewer.PdfDocument pdfDocument = PdfiumViewer.PdfDocument.Load(SourcePdf.FullName))
{
//Generate a list of page numbers to save from the PageSpecs parameter
savePages = PSI.PDF.Procs.PageSpecsToList(PageSpecs, pdfDocument.PageCount);
if (savePages == null || savePages.Count == 0)
throw new ArgumentException("PageSpecs resulted in no pages to save");
//Make sure we can process all specified pages
foreach (int i in savePages)
{
file = OutputFileBase + "-Page_" + i.ToString() + "." + ifs.Extension;
if (pdfDocument.PageCount < i)
throw new ArgumentException("Invalid page specified: " + i.ToString() + " | PDF contains " + pdfDocument.PageCount.ToString() + " pages");
if (System.IO.File.Exists(file) && !Overwrite)
throw new ArgumentException("Target image exists, overwrite not identified: " + file);
}
//Get the pages sizes array
pageSizes = (IList<System.Drawing.SizeF>)pdfDocument.PageSizes;
//Process the specified pages
foreach (int i in savePages)
{
file = OutputFileBase + "-Page_" + i.ToString() + "." + ifs.Extension;
imgWidth = (int)((pageSizes[i - 1].Width / 72) * dpiX);
imgHeight = (int)((pageSizes[i - 1].Height / 72) * dpiY);
bitmapImage = pdfDocument.Render(i-1, imgWidth, imgHeight, dpiX, dpiY, true);
bitmapImage.Save(file, ifs.ImageFmt);
savedImages.Add(file);
}
}
return savedImages;
}