.Net平台下与PDF相关的一些操作
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;//旋转角度
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转PDF
-
Aspose
- 优点:可直接使用,不依赖office,简单、方便。
- 缺点:收费,免费版有个大大的Aspose水印,网上有破解版,但是不稳定,有些文档会转换失败。
- 地址:Aspose
Aspose.Words、Aspose.Cells、Aspose.Slides分别对应word、excel、ppt的转换。
示例代码:
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
优点:免费,微软自家出品,靠谱。
缺点:依赖office,需先安装office。
-
地址:如果已安装vs,则可在本地目录D:\Program Files (x86)\Microsoft Visual Studio 11.0\Visual Studio Tools for Office\PIA\Office14路径下找到全套dll。
公司基本会选择使用免费的Office Interop
示例代码:///
/// 把Word文件转换成为PDF格式文件 /// /// 源文件路径 /// 目标文件路径 ///true=转换成功 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; }
图片转PDF
依旧itextsharp
将图片转换为PDF依旧使用的itextsharp工具,itextsharp有一套比较完整的PDF操作的工具可供我们使用,转PDF的本质是创建一个PDF文件,并将想要转换为PDF的图片插入创建的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,本质是在图片上绘制文本或图形、图像。
示例代码:
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;//旋转角度
float fontSize = 30;
float fontSizePx=fontSize*16;//将字体大小从em转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转图片
ghostscript
特点:
- 免费,简单
- 需先在本地(服务器)安装其exe文件
地址:ghostscript
根据服务器位数去官网下载相应的exe程序,一路next安装即可,然后按照如下示例代码转换即可。
示例代码:
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的每一页转为图片,由于需求的缘故,这里我只转了第一张
//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);//这里可以设置转换的图片的dpi,因为我的PDF本来就是图片转来的,所以我再转为图片的时候,设置为原图片的dpi
bitmap.Save(targetPath, format);
}
}
}
}