.netcore 使用PdfSharpCore生成pdf

想实现的功能是pdf+签名图片合并起来,后面看到了免费开源的PdfSharpCore. 

先安装

 

    public static class PdfSharpCoreHelper
    {
        private static string GetOutFilePath(string name)
        {
            string OutputDirName = @".";
            return System.IO.Path.Combine(OutputDirName, name);
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="document">PdfDocument</param>
        /// <param name="name">文件名</param>
        private static void SaveDocument(PdfSharpCore.Pdf.PdfDocument document, string name)
        {
            string outFilePath = GetOutFilePath(name);
            string? dir = System.IO.Path.GetDirectoryName(outFilePath);
            if (dir != null && !System.IO.Directory.Exists(dir))
            {
                System.IO.Directory.CreateDirectory(dir);
            }

            document.Save(outFilePath);
        }

        /// <summary>
        /// 将图片 文字添加到PDF文档中
        /// </summary>
        public static void ConvertSVGtoPDF()
        {
            System.Console.WriteLine("Starting...");

            //获取pdf文件
            PdfDocument document = PdfReader.Open(@"F:\svn项目\ConvertSVGtoPDF.pdf", PdfDocumentOpenMode.Modify);
            //获取第一页pdf
            PdfSharpCore.Pdf.PdfPage? pageNewRenderer = document.Pages[0];
            PdfSharpCore.Drawing.XGraphics? renderer = PdfSharpCore.Drawing.XGraphics.FromPdfPage(pageNewRenderer);
            //添加图片
            renderer.DrawImage(XImage.FromFile(@"F:\svn项目\svgdq.jpg"),
                new PdfSharpCore.Drawing.XPoint(120, 120));
            //添加文字
            renderer.DrawString(
                  "Testy Test Test"
                , new PdfSharpCore.Drawing.XFont("Arial", 12)
                , PdfSharpCore.Drawing.XBrushes.Black
                , new PdfSharpCore.Drawing.XPoint(12, 12)
            );
            //保存
            SaveDocument(document, "dsada.pdf");

    
        }
    }

  

posted @ 2024-10-20 15:00  zuiaixiaoyadan  阅读(74)  评论(0编辑  收藏  举报