如何使用C#和Windows Forms将PDF文件转换为图像格式(JPG,PNG等)?

如何使用C#和Windows Forms将PDF文件转换为图像格式(JPG,PNG等)?

问题描述:

我正在寻找一种将PDF文件转换为任何图像格式的简单解决方案。我试图避免使用付费库。



目标是在转换后显示面板内第一个PDF页面的预览。为此,我需要将文件的第一页至少转换为图像格式。我将不得不将代码栏标记到文件中,然后将其转换回PDF(虽然这部分不是问题)。



如果有的话我会非常感激你可以指出我正确的方向。



干杯!

I am looking for a simple solution for converting a PDF file into any image format. I am trying to avoid using paid libraries.

The goal is to, after converion, show a preview of the first PDF page inside a panel. To accomplish that, I need to convert at least the first page of the file into an image format. I will have to stamp a code bar into the file, then convert it back to PDF (although this part is not the problem).

I would greatly appreciate if any of you could point me in the right direction.

Cheers!

我一般用 GhostScript [ ^ ]对于这种类型的转换。



可以在进程中加载​​DLL并使用P / Invoke来调用它,但我通常会使用命令行版本。这样,腐败或非常大的PDF不会影响我的申请。



如何使用Ghostscript API将PDF转换为图像 [ ^ ]
I generally use GhostScript[^] for this type of conversion.

It's possible to load the DLL in-process and use P/Invoke to call it, but I usually shell out to the command-line version. That way, a corrupt or very large PDF won't affect my application.

How To Convert PDF to Image Using Ghostscript API[^]


//打开并加载文件

使用(FileStream fs = new FileStream(@Documents\TestFile.pdf,FileMode.Open))

{

//此对象代表PDF文档

文档文档=新文档(fs);



//默认渲染设置

RenderingSettings settings = new RenderingSettings();



//逐个处理和保存页面

for(int i = 0; i< document.Pages.Count; i ++)

{

Page currentPage = document.Pages [i];


//我们使用原始页面的图像宽度和高度以及默认渲染设置

using(Bitmap bitmap = currentPage.Render(( int)currentPage.Width,(int)currentPage.Height,settings))

{

bitmap.Save(string.Format({0} .png,i ),ImageFormat.Png);

}

}

//预览第一个渲染页面

Process.Start (0.png);

}
// open and load the file
using (FileStream fs = new FileStream(@"Documents\TestFile.pdf", FileMode.Open))
{
// this object represents a PDF document
Document document = new Document(fs);

// default rendering settings
RenderingSettings settings = new RenderingSettings();

// process and save pages one by one
for (int i = 0; i < document.Pages.Count; i++)
{
Page currentPage = document.Pages[i];

// we use original page's width and height for image as well as default rendering settings
using (Bitmap bitmap = currentPage.Render((int)currentPage.Width, (int)currentPage.Height,settings))
{
bitmap.Save(string.Format("{0}.png", i), ImageFormat.Png);
}
}
// preview first rendered page
Process.Start("0.png");
}