.Net平台下PDF相关

.Net平台下与PDF相关的一些操作

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;//旋转角度
                    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
      示例代码:

      /// <summary>
      /// 把Word文件转换成为PDF格式文件
      /// </summary>
      /// <param name="sourcePath">源文件路径</param>
      /// <param name="targetPath">目标文件路径</param>
      /// <returns>true=转换成功</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;
      }
      

图片转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);
            }
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 227,488评论 6 531
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 98,034评论 3 414
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 175,327评论 0 373
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 62,554评论 1 307
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 71,337评论 6 404
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 54,883评论 1 321
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 42,975评论 3 439
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 42,114评论 0 286
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 48,625评论 1 332
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 40,555评论 3 354
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 42,737评论 1 369
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 38,244评论 5 355
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 43,973评论 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 34,362评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 35,615评论 1 280
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 51,343评论 3 390
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 47,699评论 2 370

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,776评论 18 139
  • 小编今天分享一下自己的成长风趣幽默的一面。想知道的谜底的帅哥美女往下读,稍后精彩呈现…… 在我很小的时候...
    dearxuting阅读 257评论 0 0
  • 已经不记得是从哪里看到的,是谁推荐的这本书。但是,可以确定的是,推荐人并没有告诉我它是一本后现代的小说。 于我而言...
    河里没有灯阅读 532评论 0 2
  • my @cancer = grep{!$_{$_}++}@Cancer;
    白云梦_7阅读 306评论 0 0
  • 还记得自己曾经傻乎乎的问过身边同学,室友都回家了只剩你一人不孤独不害怕吗?人家只是微微一笑然后说了句”还好吧”...
    阿布吉岛阅读 168评论 0 0