C#操作PDF文件--PDFBox讀取pdf文件,O2S.Components.PDFRender4NET生成縮圖
二、引用動態連結庫
解壓縮下載的PDFBox,找到其中的Bin目錄,需要在專案中新增引用的dll檔案有:
IKVM.GNU.Classpath.dll
PDFBox-0.7.3.dll
FontBox-0.1.0-dev.dll
IKVM.Runtime.dll
將以上4個檔案引用到專案中,在檔案中需要引入以下2個名稱空間:
using org.pdfbox.pdmodel;
using org.pdfbox.util;
三、API的使用方法
using System.IO;
using System.Text;
using org.pdfbox.pdmodel;
using org.pdfbox.util;
namespace PDFReader
{
class Program
{
public static void pdf2txt(FileInfo pdffile, FileInfo txtfile)
{
PDDocument doc = PDDocument.load(pdffile.FullName);
PDFTextStripper pdfStripper = new PDFTextStripper();
string text = pdfStripper.getText(doc);
StreamWriter swPdfChange = new StreamWriter(txtfile.FullName, false, Encoding.GetEncoding("gb2312"));
swPdfChange.Write(text);
swPdfChange.Close();
}
static void Main(string[] args)
{
pdf2txt(new FileInfo(@"D:\1.pdf"), new FileInfo(@"D:\1.txt"));
}
}
}
二、運用O2S.Components.PDFRender4NET.dll對PDF文件生成縮圖
程式碼如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using O2S.Components.PDFRender4NET;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
namespace O2S.Components.PDFRender4NET.pdf2image
{
public static class Program
{
public enum Definition
{
One = 1, Two = 2, Three = 3, Four = 4, Five = 5, Six = 6, Seven = 7, Eight = 8, Nine = 9, Ten = 10
}
/// <summary>
/// 將PDF文件轉換為圖片的方法
/// </summary>
/// <param name="pdfInputPath">PDF檔案路徑</param>
/// <param name="imageOutputPath">圖片輸出路徑</param>
/// <param name="imageName">生成圖片的名字</param>
/// <param name="startPageNum">從PDF文件的第幾頁開始轉換</param>
/// <param name="endPageNum">從PDF文件的第幾頁開始停止轉換</param>
/// <param name="imageFormat">設定所需圖片格式</param>
/// <param name="definition">設定圖片的清晰度,數字越大越清晰</param>
public static void ConvertPDF2Image(string pdfInputPath, string imageOutputPath,
string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat, Definition definition)
{
PDFFile pdfFile = PDFFile.Open(pdfInputPath);
if (!Directory.Exists(imageOutputPath))
{
Directory.CreateDirectory(imageOutputPath);
}
// validate pageNum
if (startPageNum <= 0)
{
startPageNum = 1;
}
if (endPageNum > pdfFile.PageCount)
{
endPageNum = pdfFile.PageCount;
}
if (startPageNum > endPageNum)
{
int tempPageNum = startPageNum;
startPageNum = endPageNum;
endPageNum = startPageNum;
}
// start to convert each page
for (int i = startPageNum; i <= endPageNum; i++)
{
Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)definition);
pageImage.Save(imageOutputPath + imageName + i.ToString() + "." + imageFormat.ToString(), imageFormat);
pageImage.Dispose();
}
pdfFile.Dispose();
}
public static void Main(string[] args)
{
ConvertPDF2Image("D:\\1.pdf", "D:\\", "A", 1, 5, ImageFormat.Jpeg, Definition.One);
}
}
}