.Net平臺下與PDF相關(guān)的一些操作
PDF添加水印
itextsharp
- 特點:開源
- 地址:itextsharp
示例代碼:
public void setWatermarkForPDF(string sourcePath, string targetPath, string waterMarkText)
{
if (!File.Exists(sourcePath))
{
throw new FileNotFoundException("源文件不存在!");
}
if (Path.GetExtension(sourcePath).ToUpper() != ".PDF")
{
throw new FormatException("源文件非PDF文件!")
}
if (File.Exists(targetPath))
{
File.Delete(targetPath);
}
BaseFont bfChinese = BaseFont.CreateFont(@"C:\Windows\Fonts\simkai.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
using (PdfReader reader = new PdfReader(sourcePath))
{
using (FileStream outputfs = new FileStream(targetPath, FileMode.Create))
{
using (PdfStamper pdfStamper = new PdfStamper(reader, outputfs))
{
iTextSharp.text.Document d = new iTextSharp.text.Document();
//PdfWriter pf = PdfWriter.GetInstance(d, new FileStream(outputfilepath, FileMode.Create));
for (int i = 1; i <= reader.NumberOfPages; i++)
{
iTextSharp.text.Rectangle pageSize = reader.GetPageSizeWithRotation(i);
PdfContentByte pageContents = pdfStamper.GetOverContent(i);
pageContents.BeginText();
float textAngle = 20.0f;//旋轉(zhuǎn)角度
float fontSize = 30;
pageContents.SetFontAndSize(bfChinese, fontSize);
//pageContents.SetRGBColorFill(169, 169, 169);
pageContents.SetColorFill(BaseColor.GRAY);
PdfGState gs = new PdfGState();
gs.FillOpacity = 0.3f;//透明度
pageContents.SetGState(gs);
pageContents.ShowTextAligned(PdfContentByte.ALIGN_LEFT, waterMarkText,100,100,textAngle);
pageContents.EndText();
pdfStamper.FormFlattening = true;
}
}
}
}
}
Office轉(zhuǎn)PDF
-
Aspose
- 優(yōu)點:可直接使用,不依賴office,簡單、方便。
- 缺點:收費,免費版有個大大的Aspose水印,網(wǎng)上有破解版,但是不穩(wěn)定,有些文檔會轉(zhuǎn)換失敗。
- 地址:Aspose
Aspose.Words、Aspose.Cells、Aspose.Slides分別對應(yīng)word、excel、ppt的轉(zhuǎn)換。
示例代碼:
privite void ConvertWordToPDF(string sourcePath,string targetPath) { Document doc = new Document(sourcePath); doc.Save(targetPath, Aspose.Words.SaveFormat.Pdf); } privite void ConvertExcelToPDF(string sourcePath,string targetPath) { Workbook excel = new Workbook(sourcePath); excel.Save(targetPath, Aspose.Cells.SaveFormat.Pdf); } privite void ConvertPptToPDF(string sourcePath,string targetPath) { Presentation ppt = new Presentation(sourcePath); ppt.Save(targetPath, Aspose.Slides.Export.SaveFormat.Pdf); } privite void ConvertPptxToPDF(string sourcePath,string targetPath) { Pptx.PresentationEx pptx = new Presentation(sourcePath); pptx.Save(targetPath, Aspose.Slides.Export.SaveFormat.Pdf); } -
Office Interop
優(yōu)點:免費,微軟自家出品,靠譜。
缺點:依賴office,需先安裝office。
-
地址:如果已安裝vs,則可在本地目錄D:\Program Files (x86)\Microsoft Visual Studio 11.0\Visual Studio Tools for Office\PIA\Office14路徑下找到全套dll。
公司基本會選擇使用免費的Office Interop
示例代碼:/// <summary> /// 把Word文件轉(zhuǎn)換成為PDF格式文件 /// </summary> /// <param name="sourcePath">源文件路徑</param> /// <param name="targetPath">目標(biāo)文件路徑</param> /// <returns>true=轉(zhuǎn)換成功</returns> public static bool ConvertWordToPDF(string sourcePath, string targetPath) { bool result = false; Microsoft.Office.Interop.Word.WdExportFormat exportFormat = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF; Microsoft.Office.Interop.Word.ApplicationClass application = null; Microsoft.Office.Interop.Word.Document document = null; try { application = new Microsoft.Office.Interop.Word.ApplicationClass(); application.Visible = false; document = application.Documents.Open(sourcePath); document.SaveAs2(); document.ExportAsFixedFormat(targetPath, exportFormat); result = true; } catch (Exception e) { result = false; } finally { if (document != null) { document.Close(); document = null; } if (application != null) { application.Quit(); application = null; } GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } return result; }
圖片轉(zhuǎn)PDF
依舊itextsharp
將圖片轉(zhuǎn)換為PDF依舊使用的itextsharp工具,itextsharp有一套比較完整的PDF操作的工具可供我們使用,轉(zhuǎn)PDF的本質(zhì)是創(chuàng)建一個PDF文件,并將想要轉(zhuǎn)換為PDF的圖片插入創(chuàng)建的PDF文件中,該方式可添加多張圖片。
示例代碼
public void ConvertImgToPDF(string sourcePath, string targetPath)
{
if (!File.Exists(sourcePath))
{
throw new FileNotFoundException("源文件不存在!");
}
if (!CCM.Current.EOAEntry.ImageTypeList.Contains(Path.GetExtension(sourcePath)))
{
throw new FormatException("源文件非圖片格式!");
}
if (File.Exists(targetPath))
{
File.Delete(targetPath);
}
using (Document doc=new Document ())
{
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(sourcePath);
img.SetDpi(72, 72);
doc.SetPageSize(new iTextSharp.text.Rectangle(img.Width, img.Height));
doc.SetMargins(0, 0, 0, 0);
using (FileStream fs=new FileStream (targetPath,FileMode.OpenOrCreate,FileAccess.Write))
{
using (PdfWriter writer=PdfWriter.GetInstance(doc,fs))
{
doc.Open();
doc.NewPage();
doc.Add(img);
doc.Close();
}
}
}
}
圖片添加水印
使用.net自帶的Graphics,本質(zhì)是在圖片上繪制文本或圖形、圖像。
示例代碼:
public void setWatermarkForImg(string sourcePath, string targetPath, string waterMarkText)
{
ImageFormat format = null;
switch (Path.GetExtension(sourcePath).ToUpper())
{
case ".JPG":
case ".JPEG":
format = ImageFormat.Jpeg;
break;
case ".TIF":
case ".TIFF":
format = ImageFormat.Tiff;
break;
case ".PNG":
format = ImageFormat.Png;
break;
default:
throw new FormatException("不支持的文件格式!");
}
Bitmap bitmap = new Bitmap(sourcePath);
float textAngle = 20.0f;//旋轉(zhuǎn)角度
float fontSize = 30;
float fontSizePx=fontSize*16;//將字體大小從em轉(zhuǎn)px,這邊不確定fontSize的30是什么單位
System.Drawing.Font font = new System.Drawing.Font("宋體", fontSize, FontStyle.Bold);
Brush backbrush = new SolidBrush(Color.Transparent);//背景色
Brush frontbrush = new SolidBrush(Color.DarkGray);//前景色
float textlength = maxWaterMarkLength * fontSizePx;//字長
float textwidth = (float)Math.Cos(textAngle * 2 * Math.PI / 360) * textlength;//水平寬度
float textheight = (float)Math.Sin(textAngle * 2 * Math.PI / 360) * textlength;//垂直高度
if (File.Exists(targetPath))
{
File.Delete(targetPath);
}
for (int i = 0; i < 6; i++)
{
bitmap = new Bitmap(sourcePath);
using (Graphics g = Graphics.FromImage(bitmap))
{
g.RotateTransform(-textAngle);
g.FillRectangle(backbrush, (bitmap.Width - textwidth) * 1 / 2, (bitmap.Height - 2 * textheight) * 1 / 4 - j * 50, textwidth, textheight);
g.DrawString(waterMarkTexts[j], font, frontbrush, (bitmap.Width - textwidth) * 1 / 2, (float)((bitmap.Height - 2 * textheight) * 1 / 4 + j * fontSizePx*1.5));
using (MemoryStream ms = new MemoryStream())
{
bitmap.Save(sourcePath, format);
}
}
}
}
PDF轉(zhuǎn)圖片
ghostscript
特點:
- 免費,簡單
- 需先在本地(服務(wù)器)安裝其exe文件
地址:ghostscript
根據(jù)服務(wù)器位數(shù)去官網(wǎng)下載相應(yīng)的exe程序,一路next安裝即可,然后按照如下示例代碼轉(zhuǎn)換即可。
示例代碼:
public void ConvertPDFToImg(string sourcePath, string targetPath,string ext,float dpiX,float dpiY)
{
int pageDpiX = 72;//PDF的dpi
int pageDpiY = 72;
if (!File.Exists(sourcePath))
{
throw new FileNotFoundException("源文件不存在!");
}
if (Path.GetExtension(sourcePath).ToUpper()!=".PDF")
{
throw new IOException("源文件非PDF格式!");
}
if (File.Exists(targetPath))
{
File.Delete(targetPath);
}
ImageFormat format = ImageFormat.Jpeg;
switch (ext.ToUpper())
{
case ".JPG":
case ".JPEG":
format = ImageFormat.Jpeg;
break;
case ".TIF":
case ".TIFF":
format = ImageFormat.Tiff;
break;
case ".PNG":
format = ImageFormat.Png;
break;
default:
throw new BadImageFormatException("不支持的圖片格式");
}
using (var rasterizer = new GhostscriptRasterizer())
{
rasterizer.Open(sourcePath);
//可以將PDF的每一頁轉(zhuǎn)為圖片,由于需求的緣故,這里我只轉(zhuǎn)了第一張
//for (var pageNumber = 1; pageNumber <= rasterizer.PageCount; pageNumber++)
//{
// var img = rasterizer.GetPage(desired_x_dpi, desired_y_dpi, pageNumber);
// img.Save(targetPath, format);
//}
if (rasterizer.PageCount>=1)
{
var img = rasterizer.GetPage(pageDpiX, pageDpiY, 1);
using (Bitmap bitmap = new Bitmap(img))
{
bitmap.SetResolution(dpiX, dpiY);//這里可以設(shè)置轉(zhuǎn)換的圖片的dpi,因為我的PDF本來就是圖片轉(zhuǎn)來的,所以我再轉(zhuǎn)為圖片的時候,設(shè)置為原圖片的dpi
bitmap.Save(targetPath, format);
}
}
}
}