.Net平台下PDF相关

2018-09-08  本文已影响52人  程序员小逗逼

.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

图片转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

特点:

地址: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);
            }
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读