由于无法渲染或光栅化PDF文件中的矢量图形,因此您无法使用iText进行此操作。
选项1:
如果GPL许可证为你工作,你可以用栅格化的ImageMagick + GNU Ghostscript的PDF文件,但据我所知,你必须将输出写入在这种情况下的文件。
命令行示例:
convert -density 300 -depth 8 c:\temp\mydoc.pdf c:\temp\myrasterimage.png
也有在Codeplex上一个.NET的包装,可能会为你工作:ImageMagick.NET
选项A:
如果商业图书馆是一种选择你,你可以试试Amyuni PDF Creator .Net。您可以使用方法IacDocument.ExportToJpg,该方法需要写入文件,或者您可以使用方法IacDocument.DrawCurrentPage,这对于将输出写入存储器流非常有用。
const int twipsPerInch = 1440;
const int MM_ISOTROPIC = 7;
private static MemoryStream RasterizePDF(string filePath, int pageIndex, int targetDPI)
{
Amyuni.PDFCreator.IacDocument doc = new Amyuni.PDFCreator.IacDocument();
doc.SetLicenseKey("Evaluation", "07EFC00...77C23E29");
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
doc.Open(fs, "");
//Get the width and height of the target page
Amyuni.PDFCreator.IacPageFormat format = doc.GetPage(pageIndex).GetPageFormat();
doc.CurrentPageNumber = pageIndex;
//Create Image
Bitmap img = new Bitmap((int)(format.Width * targetDPI/twipsPerInch), (int)(format.Length * targetDPI/twipsPerInch), PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(img);
//set image object background to white
g.Clear(Color.White);
//Get a device context for the grahics object
IntPtr hdc = g.GetHdc();
SetMapMode(hdc, MM_ISOTROPIC);
// set scaling factor
SetWindowExtEx(hdc, twipsPerInch, twipsPerInch, 0);
SetViewportExtEx(hdc, targetDPI, targetDPI, 0);
//draw the contents of the PDF document on to the graphic context
doc.DrawCurrentPage(hdc, false);
//clean up
g.ReleaseHdc(hdc);
g.Dispose();
// Save the bitmap as png into the resulting stream
MemoryStream resultStrm = new MemoryStream();
img.Save(resultStrm, ImageFormat.Png);
//Prepare the stream to be read later on
resultStrm.Position = 0;
}
[System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
private static extern int SetMapMode(IntPtr hdc, int MapMode);
[System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
private static extern int SetWindowExtEx(IntPtr hdc, int nXExtent, int nYExtent, int not_used);
[System.Runtime.InteropServices.DllImportAttribute("gdi32.dll")]
private static extern int SetViewportExtEx(IntPtr hdc, int nXExtent, int nYExtent, int not_used);
免责声明:导出使用IacDocument.DrawCurrentPage
一个页面到内存流
示例代码中,我目前的工作作为库的开发
来源
2013-05-17 18:43:03
yms
这听起来像是一次性用例。由于您的客户创建了图像并将其提供给您,您是否可以请求他们仅以PNG格式提供图像?或者你可以打开PDF文件,在屏幕上调整你想要的尺寸,并做一个屏幕截图。 – mbmcavoy
不幸的是,客户端将提供像这样的所有图像。原因是因为该网站会根据图片大小要求吐出不同大小的图片,或者如果用户想要,他们可以下载它的矢量版本。 – JohnathanKong
好吧,这样就会有大量的图片需要处理?尽管如此,这看起来像PDF是一种糟糕的格式选择。也许SVG?由于这是一个广泛支持的开放格式,我相信您可以按需编程转换为PNG或PDF格式。 – mbmcavoy