在实际应用中,我们常常需要处理PDF文件的各种转换需求,其中之一便是将一个多页的PDF文档转换成一张连续的图片,这对于制作演示文稿、网页展示或者电子书预览等场景尤为实用。这里使用Free Spire.PDF for .NET类库来实现这个功能。
Free Spire.PDF for .NET作为一个独立的免费PDF优秀类库,使用它不需要在系统上安装 Adobe Acrobat 或任何其他第三方软件/库,可以在.NET应用程序中实现pdf转换为图像,当然也可以支持把其他文档格式的文件转换为pdf文件。
转换功能:支持pdf转换为图像、也支持文档转换为pdf
安全功能:通过设置密码和数字签名保护 PDF 文档、 解密 PDF 文档、 获取并验证数字签名、 修改 PDF 密码
pdf文档处理:合并/拆分 PDF 文档、叠加文档、导入和添加印章功能
其他功能:从 PDF 文档中提取图像、文本、页面和附件、支持图层、透明图形、颜色空间和条形码创建、插入交互式元素等
• 将网页 HTML、HTML ASPX 转换为 PDF
• 将图像(Jpeg、Jpg、Png、Bmp、Tiff、Gif、EMF、Ico)转换为 PDF
• 将文本转换为 PDF
• 将 RTF 转换为 PDF
• 将 PDF 转换为图像
打开Nuget管理界面,输入 “FreeSpire.PDF” 进行检索,检索结果第一项就是需要安装的类库,大家根据自己的Net版本选择相应的类库版本。
工具→Nuget包管理器→程序包管理器控制台
输入如下命令:
Install-Package FreeSpire.PDF -Version 8.6.0
新增类库 PdfToImageConverter.cs
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PdfToImage
{
public class PdfToImageConverter
{
private const int Dpi = 500;
public static void ConvertPdfToVerticalImage(string inputPdfPath, string outputImagePath)
{
// 初始化PDF文档对象和总高度计数器
PdfDocument doc = null;
float totalHeightInPixels = 0f;
try
{
// 加载PDF文档
doc = new PdfDocument();
doc.LoadFromFile(inputPdfPath);
List<Image> list = new List<Image>();
int i = 0;
int totalHeight = 0;
int maxWidth = 0;
// 计算所有页面的总高度
foreach (PdfPageBase page in doc.Pages)
{
totalHeightInPixels += page.Size.Height;
Image image = doc.SaveAsImage(i, PdfImageType.Bitmap, 500, 500);
list.Add(image);
i++;
totalHeight += image.Height;
if (maxWidth < image.Width)
{
maxWidth = image.Width;
}
image.Save(@"E:\测试\combined_image0410"+i+".png", ImageFormat.Png);
}
Bitmap combinedImage = new Bitmap(maxWidth, totalHeight);
int mheight = 0;
using (Graphics g = Graphics.FromImage(combinedImage))
{
g.Clear(Color.Transparent); // 清空背景为透明(或者选择其他颜色)
foreach(Image image in list)
{
// 绘制第一张图片在顶部
g.DrawImage(image, 0, mheight, maxWidth, image.Height);
mheight += image.Height;
image.Dispose();
}
}
combinedImage.Save(@"E:\测试\combined_image0410.png", ImageFormat.Png);
combinedImage.Dispose();
}
finally
{
// 确保PDF文档被正确关闭和释放资源
doc?.Dispose();
}
}
}
}
调用实例Program.cs
using System;
using System.Collections.Generic;
using System.IO;
namespace PdfToImage
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
// 指定PDF文件路径
string inputPdfPath = @"E:\测试\test.pdf";
string outputImagePath = @"E:\测试\test.png";
PdfToImageConverter.ConvertPdfToVerticalImage(inputPdfPath, outputImagePath);
}
}
注意:目前支持前三页转换,如果需要实现超过三页的话,需要考虑授权的类库。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。