用C#将多个jpg合成一个pdf

nuget安装iTextSharp

static void MergePDF(string picPath,string pdfPath)
        {
            string[] picFileNames=Directory.GetFiles(picPath, "*");
            List<string> fileNames = picFileNames.ToList();
            fileNames.Sort((l,r)=> {
                int lnum = int.Parse(Path.GetFileName(l).Replace(".jpg",""));
                int rnum = int.Parse(Path.GetFileName(r).Replace(".jpg",""));
                return lnum.CompareTo(rnum);
            });
            Document document = new Document(new Rectangle(2100,1488));//设定pdf的大小
            PdfWriter.GetInstance(document, new FileStream(pdfPath, FileMode.Create));
            document.Open();
            foreach (string jpgPath in fileNames)
            {
                Image jpgImage = Image.GetInstance(jpgPath);

                jpgImage.ScaleToFit(document.PageSize.Width, document.PageSize.Height);//调整图片的大小

                document.Add(jpgImage);
            }
            document.Close();
        }

如果报错:PdfWriter.GetInstance未将对象引用设置到对象的实例.
VS设置为调试仅我的代码。

posted @ 2023-05-09 22:05  JohnYang819  阅读(228)  评论(0编辑  收藏  举报