PDF 与图片互转

使用 Aspose.PDF 包进行 PDF 和图片间的相互转换,Aspose.PDF 是一个收费组件,但可以申请试用

安装 Aspose.PDF 包

1
Install-Package Aspose.Pdf

申请试用

可以在 Aspose官方网站 申请试用,需要提供可以接收邮件的邮箱,申请通过之后会收到一封包含 Aspose.Pdf.lic 文件下载链接的邮件。
需要将下载的 Aspose.Pdf.lic 文件放到程序根目录。

PDF 转图片

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/// <summary>
/// PDF To Image
/// </summary>
public static void ToImage()
{
License license = new License();
license.SetLicense("Aspose.Pdf.lic");

// 获取工作目录
string path = Directory.GetCurrentDirectory() + "/";

// 打开文档
Document pdfDocument = new Document(path + "PDF_To_Image.pdf");

for (int pageCount = 1; pageCount <= 2; pageCount++)
{
FileStream imageStream = new FileStream(path + "PDF_To_Image/" + pageCount + ".png", FileMode.Create);
// 创建具有指定属性的PNG设备
// 宽度,高度,分辨率,质量
// Width, Height, Resolution, Quality
// Quality [0-100], 100 is Maximum
// Create Resolution object
//Resolution resolution = new Resolution(300);
PngDevice pngDevice = new PngDevice();

// 转换特定页面并将图像保存到流
pngDevice.Process(pdfDocument.Pages[pageCount], imageStream);

// 关闭stream对象
imageStream.Close();
}
}

图片转 PDF

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/// <summary>
/// Image To PDF
/// </summary>
public static void ToPDF()
{
License license = new License();
license.SetLicense("Aspose.Pdf.lic");


// 获取工作目录
string path = Directory.GetCurrentDirectory() + "/";
// 实例化文档对象
Document doc = new Document();

MemoryStream mystream = null;

int count = 2;
for (int pageCount = 1; pageCount <= count; pageCount++)
{
// 将页面添加到文档的页面集合
Page page = doc.Pages.Add();

// 将源图像文件加载到Stream对象
FileStream fs = new FileStream(path + pageCount + ".png", FileMode.Open, FileAccess.Read);
byte[] tmpBytes = new byte[fs.Length];
fs.Read(tmpBytes, 0, int.Parse(fs.Length.ToString()));

mystream = new MemoryStream(tmpBytes);

// 使用加载的图像流实例化BitMap对象
Bitmap b = new Bitmap(mystream);

// 设置边距以便图像适合
page.PageInfo.Margin.Bottom = 0;
page.PageInfo.Margin.Top = 0;
page.PageInfo.Margin.Left = 0;
page.PageInfo.Margin.Right = 0;

page.CropBox = new Aspose.Pdf.Rectangle(0, 0, b.Width, b.Height);

// 创建一个图像对象
Aspose.Pdf.Image image = new Aspose.Pdf.Image();

// 将图像添加到本节的段落集合中
page.Paragraphs.Add(image);

// 设置图像文件流
image.ImageStream = mystream;
}
path = path + "Image_To_PDF.pdf";
// 保存结果PDF文件
doc.Save(path);

// 关闭memoryStream对象
mystream.Close();
}

Source code

PDF.Tools