参考文档 :https://www.cnblogs.com/ibeisha/p/itextsharp-pdf.html

程序demo 地址:https://github.com/hudean/itextsharpDemo

 

我这边收到一份word版的文档,首先,我们将其另存为PDF文件。其次,在https://www.pdfescape.com/open/这个网站,将PDF文件上传上去,进行在线编辑。 

 

 

也可以通过PDF软件工具,进行编辑。这里,我把需要填写部分的内容,全画上表单元素,设置元素的name,后面根据name 属性对其进行赋值。具体操作,将text放置指定处,然后鼠标右键,看到如下界面:

 

 这里Name属性就是后面我们要用到的。目前它支持的元素有:

 

 

1、使用itextsharp 生成pdf文件 引用itextsharp 包

DataTable 转成pdf文件

 private static void Method()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("id", typeof(int));
            dt.Columns.Add("name", typeof(string));
            dt.Columns.Add("age", typeof(int));
            dt.Columns.Add("address", typeof(string));
            dt.Clear();
            DataRow dr = dt.NewRow();
            dr["id"] = 1; dr["name"] = "cscc"; dr["age"] = 26; dr["address"] = "江西省";
            dt.Rows.Add(dr);
            dt.AcceptChanges();
            bool b = ITextSharpHelper2.ConvertDataTableToPDF(dt, @"C:\Users\Administrator\Desktop\testPDF.pdf", "C://WINDOWS//FONTS//SIMSUN.TTC,1", 9);
            Console.WriteLine($"{b}");
            Console.ReadKey();
        }

ITextSharpHelper2帮助类

public class ITextSharpHelper2
    {
        /// <summary>
        /// 根据pdf模板写入数据生成新的pdf
        /// </summary>
        /// <param name="saveFile">保存的新pdf路径</param>
        /// <param name="sourceFile">原pdf路径</param>
        public static void AddNewPdf(string saveFile, string sourceFile)
        {
            //写入新的pdf地址
            //sourceFile = @"C:\Users\Administrator\Desktop\ABC\temp.pdf";
            //sourceFile = @"C:\Users\Administrator\Desktop\temp123.pdf";
            iTextSharp.text.pdf.PdfDocument document = new iTextSharp.text.pdf.PdfDocument();
            //读取的源pdf文件
            iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(sourceFile);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(saveFile, FileMode.OpenOrCreate));
            AcroFields pdfFormFields = pdfStamper.AcroFields;
            pdfStamper.FormFlattening = true;
            //BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            //BaseFont simheiBase = BaseFont.CreateFont(@"C:\Windows\Fonts\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            BaseFont simheiBase = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            pdfFormFields.AddSubstitutionFont(simheiBase);
            Dictionary<string, string> para = new Dictionary<string, string>();
            para.Add($"Numbering", "12369999995");
            for (int i = 1; i < 38; i++)
            {
                para.Add($"Numbering{i}", "12365");
            }
            foreach (KeyValuePair<string, string> parameter in para)
            {
                pdfStamper.AcroFields.SetField(parameter.Key, parameter.Value);
            }
            //pdfStamper.AcroFields.SetField("Names", "李朝强");
            //pdfStamper.AcroFields.SetField("chk", "yes", true);
            pdfStamper.Close();
            pdfReader.Close();
        }

        /// <summary>
        /// pdf文件添加图片
        /// </summary>
        /// <param name="oldPath">源PDF文件</param>
        /// <param name="newPath">新PDF文件</param>
        /// <param name="imPath">图片地址</param>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public static void AddImg(string oldPath, string newPath, string imPath, float x, float y)
        {
            iTextSharp.text.pdf.PdfDocument doc = new iTextSharp.text.pdf.PdfDocument();


            iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(oldPath);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newPath, FileMode.OpenOrCreate));
            //获取PDF指定页面内容
            var pdfContentByte = pdfStamper.GetOverContent(1);
            //添加图片
            Image image = Image.GetInstance(imPath);

            //设置图片大小
            image.ScaleToFit(100, 100);
            //设置图片位置
            image.SetAbsolutePosition(x, y);
            pdfContentByte.AddImage(image);
            pdfStamper.FormFlattening = true;
            pdfStamper.Close();
            pdfReader.Close();

        }


        /// <summary>
        /// DataTable 转成Pdf文件
        /// </summary>
        /// <param name="Data"></param>
        /// <param name="PDFFile"></param>
        /// <param name="FontPath"></param>
        /// <param name="FontSize"></param>
        /// <returns></returns>
        public static bool ConvertDataTableToPDF(DataTable Data, string PDFFile, string FontPath, float FontSize)
        {
            Document document = new Document();
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(PDFFile, FileMode.Create));
            document.Open();
            BaseFont baseFont =
                BaseFont.CreateFont(
                FontPath,
                BaseFont.IDENTITY_H,
                BaseFont.NOT_EMBEDDED);
            iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, FontSize);
            PdfPTable table = new PdfPTable(Data.Columns.Count);
            for (int i = 0; i < Data.Rows.Count; i++)
            {
                for (int j = 0; j < Data.Columns.Count; j++)
                {
                    table.AddCell(new Phrase(Data.Rows[i][j].ToString(), font));
                }
            }
            document.Add(table);
            document.Close();
            writer.Close();
            return true;
        }

    }
View Code

调用

static void Main(string[] args)
        {
            #region  DataTable 转成pdf文件

            // Method();
            #endregion

            #region 向pdf文件添加图片

            //ITextSharpHelper2.AddImg(@"C:\Users\Administrator\Desktop\testPDF.pdf", @"C:\Users\Administrator\Desktop\tempPDF.pdf", @"C:\Users\Administrator\Desktop\QRCode.png", 300, 100);

            #endregion

            #region 向pdf模板文件添加数据

            ITextSharpHelper2.AddNewPdf(@"C:\Users\Administrator\Desktop\temp3.pdf", @"C:\Users\Administrator\Desktop\temp123.pdf");
            #endregion

            Console.ReadKey();
        }

(模板文件在程序的文件夹里,模板里要填的数据我在上面所有的属性都填写对应的名称)

Zxing 生成读取二维码帮助类,引用ZXing 包

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZXing;
using ZXing.Common;
using ZXing.QrCode;

namespace QRCode
{
    public class ZxingHelper
    {
        /// <summary>
        /// 生成二维码,保存成图片
        /// </summary>
        public static void Generate1(string text, string filename)
        {
            BarcodeWriter writer = new BarcodeWriter();
            writer.Format = BarcodeFormat.QR_CODE;
            QrCodeEncodingOptions options = new QrCodeEncodingOptions();
            options.DisableECI = true;
            //设置内容编码
            options.CharacterSet = "UTF-8";
            //设置二维码的宽度和高度
            options.Width = 500;
            options.Height = 500;
            //设置二维码的边距,单位不是固定像素
            options.Margin = 1;
            writer.Options = options;

            Bitmap map = writer.Write(text);
            //string filename = @"H:\桌面\截图\generate1.png";
            map.Save(filename, ImageFormat.Png);
            map.Dispose();
        }

        /// <summary>
        /// 生成条形码
        /// </summary>
        /// <param name="text"></param>
        public static void Generate2(string text, string filename)
        {
            BarcodeWriter writer = new BarcodeWriter();
            //使用ITF 格式,不能被现在常用的支付宝、微信扫出来
            //如果想生成可识别的可以使用 CODE_128 格式
            //writer.Format = BarcodeFormat.ITF;
            writer.Format = BarcodeFormat.CODE_128;
            EncodingOptions options = new EncodingOptions()
            {
                Width = 150,
                Height = 50,
                Margin = 2
            };
            writer.Options = options;
            Bitmap map = writer.Write(text);
            //string filename = @"H:\桌面\截图\generate2.png";
            map.Save(filename, ImageFormat.Png);
        }

        /// <summary>
        /// 读取二维码
        /// 读取失败,返回空字符串
        /// </summary>
        /// <param name="filename">指定二维码图片位置</param>
        public static string Read1(string filename)
        {
            BarcodeReader reader = new BarcodeReader();
            reader.Options.CharacterSet = "UTF-8";
            Bitmap map = new Bitmap(filename);
            Result result = reader.Decode(map);
            return result == null ? "" : result.Text;
        }
    }
}
View Code

 

ThoughtWorks 生成读取二维码帮助类,引用ThoughtWorks 包

using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ThoughtWorks.QRCode.Codec;

namespace QRCode
{
    public  class ThoughtWorksHelper
    {

        /// <summary>
        /// ThoughtWorks.QRCode生成二维码
        /// </summary>
        /// <param name="idStr">写入二维码的字符串</param>
        /// <param name="strSaveDir">保存的路径</param>
        /// <param name="fileName">保存文件名称例如 QRCode.png</param>
        /// <returns></returns>
        public static void QRCodeMehed(string idStr,string strSaveDir,string fileName)
        {
            QRCodeEncoder endocder = new QRCodeEncoder();
            //二维码背景颜色
            endocder.QRCodeBackgroundColor = System.Drawing.Color.White;
            //二维码编码方式
            endocder.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            //每个小方格的宽度
            endocder.QRCodeScale = 10;
            //二维码版本号
            endocder.QRCodeVersion = 5;
            //纠错等级
            endocder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
            //var person = new { Id = 1, Name = "wolfy", Gender = 1, Age = 24 };
            //string idStr = "134165897456321";
            //将json川做成二维码
            //Bitmap bitmap = endocder.Encode(new JavaScriptSerializer().Serialize(person), System.Text.Encoding.UTF8);
            Bitmap bitmap = endocder.Encode(idStr, System.Text.Encoding.UTF8);
            //string strSaveDir = @"C:\Users\Administrator\Desktop\ABC";//Request.MapPath("/QRcode/");
            if (!Directory.Exists(strSaveDir))
            {
                Directory.CreateDirectory(strSaveDir);
            }
            // string strSavePath = Path.Combine(strSaveDir, "QRCode" + ".png");
            string strSavePath = Path.Combine(strSaveDir, fileName);
            //System.IO.FileStream fs = new System.IO.FileStream(strSavePath, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
            //bitmap.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg);
            if (!System.IO.File.Exists(strSavePath))
            {
                bitmap.Save(strSavePath);
            }
        }

        /// <summary>
        /// ThoughtWorks.QRCode解析二维码
        /// </summary>
        /// <returns></returns>
        public static string DeCoder(string strSaveDir, string fileName)
        {
            string result = "";
            //string strSaveDir = @"C:\Users\Administrator\Desktop\ABC";//Request.MapPath("/QRcode/");
            fileName = "QRCode.png";
            if (!Directory.Exists(strSaveDir))
            {
                Directory.CreateDirectory(strSaveDir);
            }
            string strSavePath = Path.Combine(strSaveDir, fileName );
            if (System.IO.File.Exists(strSavePath))
            {
                QRCodeDecoder decoder = new QRCodeDecoder();
                result = decoder.decode(new ThoughtWorks.QRCode.Codec.Data.QRCodeBitmapImage(new Bitmap(Image.FromFile(strSavePath))));
            }

            return result;
        }
    }
}
View Code

 

Spire 读取pfd文件和插入图片和读取pdf里的图片 引用Spire包

using Spire.Pdf;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZXing;

namespace QRCode
{
    public class SpireHelper
    {
        //文档地址 https://www.e-iceblue.cn/spirepdfnet/spire-pdf-for-net-program-guide-content.html


        /// <summary>
        /// Spire插件添加二维码到PDF
        /// </summary>
        /// <param name="sourcePdf">pdf文件路径</param>
        /// <param name="sourceImg">二维码图片路径</param>
        public static void AddQrCodeToPdf(string sourcePdf, string sourceImg)
        {
            //初始化PdfDocument实例,导入PDF文件  
            Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();

            //加载现有文档
            doc.LoadFromFile(sourcePdf);
            //添加一个空白页,目的为了删除jar包添加的水印,后面再移除这一页  (没有用)
            //PdfPageBase pb = doc.Pages.Add();
            //获取第二页
            //PdfPageBase page = doc.Pages[1];
            //获取第1页
            PdfPageBase page = doc.Pages[0];
            //加载图片到Image对象
            Image image = Image.FromFile(sourceImg);

            //调整图片大小
            int width = image.Width;
            int height = image.Height;
            float scale = 0.18f;  //缩放比例0.18f;
            Size size = new Size((int)(width * scale), (int)(height * scale));
            Bitmap scaledImage = new Bitmap(image, size);

            //加载缩放后的图片到PdfImage对象
            Spire.Pdf.Graphics.PdfImage pdfImage = Spire.Pdf.Graphics.PdfImage.FromImage(scaledImage);

            //设置图片位置
            float x = 516f;
            float y = 8f;

            //在指定位置绘入图片
            //page.Canvas.DrawImage(pdfImage, x, y);
            page.Canvas.DrawImage(pdfImage, new PointF(x,y),size);
            //移除第一个页
            //doc.Pages.Remove(pb); //去除第一页水印
            //保存文档
            doc.SaveToFile(@sourcePdf);
            doc.Close();
            //释放图片资源
            image.Dispose();
        }

        /// <summary>
        /// Spire插件读取PDF中的二维码并保存二维码图片
        /// </summary>
        /// <param name="file">pdf文件路径</param>
        public static void QrCodeToPdf(string file,string fileImg)
        {
            //加载PDF文档
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(file);

            List<Image> listImages = new List<Image>();

            for (int i = 0; i < doc.Pages.Count; i++)
            {
                // 实例化一个Spire.Pdf.PdfPageBase对象
                PdfPageBase page = doc.Pages[i];

                // 获取所有pages里面的图片
                Image[] images = page.ExtractImages(true); //page.ExtractImages();
                if (images != null && images.Length > 0)
                {
                    listImages.AddRange(images);
                }

            }

            // 将提取到的图片保存到本地路径
            if (listImages.Count > 0)
            {
                for (int i = 0; i < listImages.Count; i++)
                {
                    Image image = listImages[i];
                    //image.Save(@"C:\Users\Administrator\Desktop\ABC\image" + (i + 3).ToString() + ".png", System.Drawing.Imaging.ImageFormat.Png);
                    image.Save(fileImg, System.Drawing.Imaging.ImageFormat.Png);
                }

            }
        }

        /// <summary>
        /// Spire插件读取PDF中的二维码,Zxing识别二维码
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public static string QrCodeToPdftwo(string file)
        {
            string str = "";
            //加载PDF文档
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(file);

            List<Image> listImages = new List<Image>();

            for (int i = 0; i < doc.Pages.Count; i++)
            {
                // 实例化一个Spire.Pdf.PdfPageBase对象
                PdfPageBase page = doc.Pages[i];

                // 获取所有pages里面的图片
                Image[] images = page.ExtractImages();
                if (images != null && images.Length > 0)
                {
                    listImages.AddRange(images);
                }

            }

            if (listImages.Count > 0)
            {

                //QRCodeDecoder decoder = new QRCodeDecoder();
                //var image = listImages[0];
                //str = decoder.decode(new ThoughtWorks.QRCode.Codec.Data.QRCodeBitmapImage((Bitmap)image));

                var image = listImages[0];
                ZXing.BarcodeReader reader = new ZXing.BarcodeReader();
                reader.Options.CharacterSet = "UTF-8";
                Bitmap map = new Bitmap(image);
                Result result = reader.Decode(map);
                return result == null ? "" : result.Text;
            }

            return str;
        }
    }
}
View Code

 

调用 

using Spire.Pdf;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ThoughtWorks.QRCode.Codec;
using ZXing;
using ZXing.Presentation;

namespace QRCode
{
    class Program
    {
        static void Main(string[] args)
        {

            #region 使用ThoughtWorks 生成识别二维码

            ////生成二维码
            //ThoughtWorksHelper.QRCodeMehed("123598788", @"C:\Users\Administrator\Desktop\", "QRCode.png");

            ////解析二维码
            //string str = ThoughtWorksHelper.DeCoder(@"C:\Users\Administrator\Desktop\", "QRCode.png");
            //Console.WriteLine(str);
            //Console.ReadKey();
            #endregion


            #region 使用Zxing 生成识别二维码
            //生成二维码
            //ZxingHelper.Generate1("8585855885",@"C:\Users\Administrator\Desktop\QRCode1.png");

            ////解析二维码
            //string str = ZxingHelper.Read1(@"C:\Users\Administrator\Desktop\QRCode1.png");
            //Console.WriteLine(str);
            //Console.ReadKey();
            #endregion

            #region 使用Spire 向pdf添加二维码或读取pdf文件里的二维码

            //文档地址 https://www.e-iceblue.cn/spirepdfnet/spire-pdf-for-net-program-guide-content.html

            //向pdf添加二维码
            //SpireHelper.AddQrCodeToPdf(@"C:\Users\Administrator\Desktop\testPDF.pdf", @"C:\Users\Administrator\Desktop\QRCode1.png");
            //在pdf读取二维码,并保存二维码图片
            //SpireHelper.QrCodeToPdf(@"C:\Users\Administrator\Desktop\testPDF.pdf", @"C:\Users\Administrator\Desktop\QRCode2.png");
            //在pdf读取二维码
            string str = SpireHelper.QrCodeToPdftwo(@"C:\Users\Administrator\Desktop\testPDF.pdf");
            Console.WriteLine(str);
            Console.ReadKey();
            #endregion
        }
    }
}
View Code

 

posted on 2021-02-01 15:05  青春似雨后霓虹  阅读(721)  评论(1编辑  收藏  举报