.Net平臺下PDF相關(guān)

.Net平臺下與PDF相關(guān)的一些操作

PDF添加水印

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);
            }
        }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,545評論 19 139
  • 小編今天分享一下自己的成長風(fēng)趣幽默的一面。想知道的謎底的帥哥美女往下讀,稍后精彩呈現(xiàn)…… 在我很小的時候...
    dearxuting閱讀 325評論 0 0
  • 已經(jīng)不記得是從哪里看到的,是誰推薦的這本書。但是,可以確定的是,推薦人并沒有告訴我它是一本后現(xiàn)代的小說。 于我而言...
    河里沒有燈閱讀 694評論 0 2
  • my @cancer = grep{!$_{$_}++}@Cancer;
    白云夢_7閱讀 316評論 0 0
  • 還記得自己曾經(jīng)傻乎乎的問過身邊同學(xué),室友都回家了只剩你一人不孤獨不害怕嗎?人家只是微微一笑然后說了句”還好吧”...
    阿布吉島閱讀 188評論 0 0

友情鏈接更多精彩內(nèi)容