
preface
今日一同事给我说你获取到的 pdf 文件有点不符合我们现有软件流程,你能不能将我们 pdf 文件转成图片啊!说干就干,由于以前研究过一段时间 pdf 文件的相关组件,所以我在 github 上找到我以前 star 的仓库,PdfiumViewer 开源地址: https://github.com/pvginkel/PdfiumViewer:

首先我们打开 NuGet 安装PdfiumViewer和ImageResizer.Plugins.PdfiumRenderer.Pdfium.Dll。

For a requirement, we should understand what attributes the objects we are operating on have?
Then when we get a pdf file, we should know that pdf has properties such as page number and file height and width.
For pictures, it is important for pictures to have attributes such as height, width (resolution), horizontal resolution and vertical resolution (dpi)!
Then we can start working after we understand these attributes. The first step is to load our pdf file and get the number of pages and file size of the file.
var pdf = PdfiumViewer.PdfDocument.Load(strpdfPath);
var pdfpage = pdf.PageCount;
var pagesizes = pdf.PageSizes;
Then assemble the image's height and width, as well as attributes such as horizontal resolution and vertical resolution
document.Render(pageNumber - 1, size.Width, size.Height, dpi, dpi, PdfRenderFlags.Annotations);
Finally save the picture
image.Save(stream, ImageFormat.Jpeg);
The complete code is as follows
public class PdfToImage
{
/// <summary>
///
/// </summary>
/// <param name="filePath">pdf文件路径</param>
/// <param name="picPath">picture文件路径</param>
public void PdfToPic(string filePath, string picPath)
{
var pdf = PdfiumViewer.PdfDocument.Load(filePath);
var pdfpage = pdf.PageCount;
var pagesizes = pdf.PageSizes;
for (int i = 1; i <= pdfpage; i++)
{
Size size = new Size();
size.Height = (int)pagesizes[(i - 1)].Height;
size.Width = (int)pagesizes[(i - 1)].Width;
//可以把".jpg"写成其他形式
RenderPage(filePath, i, size, picPath);
}
}
private void RenderPage(string pdfPath, int pageNumber, System.Drawing.Size size, string outputPath, int dpi = 300)
{
using (var document = PdfiumViewer.PdfDocument.Load(pdfPath))
using (var stream = new FileStream(outputPath, FileMode.Create))
using (var image = GetPageImage(pageNumber, size, document, dpi))
{
image.Save(stream, ImageFormat.Jpeg);
}
}
private static System.Drawing.Image GetPageImage(int pageNumber, Size size, PdfiumViewer.PdfDocument document, int dpi)
{
return document.Render(pageNumber - 1, size.Width, size.Height, dpi, dpi, PdfRenderFlags.Annotations);
}
}