C# iText 7 切分PDF,处理PDF页面大小,添加水印

一、itext

我要使用itext做一个pdf的页面大小一致性处理,然后再根据数据切分出需要的pdf.

iText的官网有关于它的介绍,https://itextpdf.com/ 然后在官网可以查找api文档https://api.itextpdf.com/。

其中我要使用的是itext7+,主要在iText.Kernel.Pdf 命名空间下。

二、处理PDF页面大小一致

由于原始PDF 是扫描图片合成来的,有些页面扫描的图片规格不一致,导致pdf阅读性很差。

对于这个pdf我进行处理,首先是在nuget 里面搜索 itext 进行安装,使用itext7。

处理PDF大小方法:

        public void RestPageSize(string sourcePdfPath, string outputPdfPath)
        {
            PdfReader pdfReader = null;
            PdfDocument pdfDocument = null;
            PdfWriter pdfWriter = null;
            PdfDocument outPDfDoc = null;
            try
            {
                pdfReader = new PdfReader(sourcePdfPath);
                pdfDocument = new PdfDocument(pdfReader);
                var outDir = System.IO.Path.GetDirectoryName(outputPdfPath);
                if (!Directory.Exists(outDir))
                {
                    Directory.CreateDirectory(outDir);
                }

                pdfWriter = new PdfWriter(outputPdfPath);
                outPDfDoc = new PdfDocument(pdfWriter);

                outPDfDoc.SetDefaultPageSize(PageSize.A3);


                for (int i = 1; i < pdfDocument.GetNumberOfPages() + 1; i++)
                {
                    var page = pdfDocument.GetPage(i);
                    var formXObject = page.CopyAsFormXObject(outPDfDoc);
                    var xPercent = PageSize.A3.GetWidth() / page.GetPageSize().GetWidth();
                    var yPercent = PageSize.A3.GetHeight() / page.GetPageSize().GetHeight();
                    PdfCanvas pdfCanvas = new PdfCanvas(outPDfDoc.AddNewPage());
                    pdfCanvas.AddXObjectWithTransformationMatrix(formXObject, xPercent, 0, 0, yPercent, 0, 0);
                }

                pdfWriter.Flush();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
                if (pdfDocument != null)
                {
                    pdfDocument.Close();
                }
                if (outPDfDoc != null)
                {
                    outPDfDoc.Close();
                }
                if (pdfWriter != null)
                {
                    pdfWriter.Close();
                    pdfWriter.Dispose();
                }
            }

思路:遍历原来的PDF页码,将原来的PDF页码对象拷贝PdfFormXObject到要生成的PDF文档中,首先要copy页面对象才能使用,不然直接获取的page对象是原来文档的,我们无法操作。

var formXObject = page.CopyAsFormXObject(outPDfDoc);

然后对页面进行缩放计算,我们新的PDF默认设置成A3大小,通过计算原始页面和新页面宽高比例进行缩放。

计算完成后,在新文档中使用PdfCanvas 对象新添加一页,然后将PdfFormXObject 写入到新添加的页中。

处理后的PDF:

三、切分PDF

切分PDF 就比较简单了,直接从原始文件中拷贝页面到新PDF文档中就行了。

切分PDF 方法:

        public void ExtractPages(string sourcePdfPath, string outputPdfPath, int startPage, int endPage)
        {
            PdfReader pdfReader = null;
            PdfDocument pdfDocument = null;
            PdfWriter pdfWriter = null;
            PdfDocument outPDfDoc = null;
            try
            {
                pdfReader = new PdfReader(sourcePdfPath);
                pdfDocument = new PdfDocument(pdfReader);
                var outDir = Path.GetDirectoryName(outputPdfPath);
                if (!Directory.Exists(outDir))
                {
                    Directory.CreateDirectory(outDir);
                }
                
                pdfWriter = new PdfWriter(outputPdfPath);
                outPDfDoc = new PdfDocument(pdfWriter);

                pdfDocument.CopyPagesTo(startPage, endPage, outPDfDoc);
                pdfWriter.Flush();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);

            }
            finally
            {
                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
                if (pdfDocument != null)
                {
                    pdfDocument.Close();
                }
                if (outPDfDoc != null)
                {
                    outPDfDoc.Close();
                }

                if (pdfWriter != null)
                {
                    pdfWriter.Close();
                    pdfWriter.Dispose();
                }
            }

        }

注意:对写入流要进行pdfWriter.Flush()将缓冲区数据写入PDF后再关。

四、添加PDF图片水印

        public static void SetWatermark(string sourcePdfPath, string outputPdfPath)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(sourcePdfPath), new PdfWriter(outputPdfPath));
            Document document = new Document(pdfDoc);
            PdfCanvas over;
            PdfExtGState gs1 = new PdfExtGState();
            //gs1.SetFillOpacity(0.6f);
            int n = pdfDoc.GetNumberOfPages();
            iText.Kernel.Geom.Rectangle pagesize;
            float x, y;
            //Bitmap image = new Bitmap("water.png");
            //image = ImageRotate(image, -45, Color.Transparent);
            var image = RotateImg(Image.FromFile("water.png"), -45);
            ImageData img = ImageDataFactory.Create(image, null);
            float w = img.GetWidth();
            float h = img.GetHeight();

            for (int i = 1; i <= n; i++)
            {
                PdfPage pdfPage = pdfDoc.GetPage(i);
                pagesize = pdfDoc.GetPage(i).GetPageSize();
                pdfPage.SetIgnorePageRotationForContent(true);

                x = (pagesize.GetLeft() + pagesize.GetRight()) / 2;
                y = (pagesize.GetTop() + pagesize.GetBottom()) / 2;
                over = new PdfCanvas(pdfDoc.GetPage(i));

                over.SaveState();
                over.SetExtGState(gs1);

                over.AddImageWithTransformationMatrix(img, w, 0, 0, h, x - (w / 2), y - (h / 2), true);
                over.RestoreState();
            }
            document.Close();
            pdfDoc.Close();
        }
posted @ 2022-04-26 11:50  XSpringSun  阅读(2382)  评论(2编辑  收藏  举报