C# 批量打印图片,Image转PDF并可多台打印机打印(Spire.PDF、去水印)

版本:一定要是Spire.PDF 5.10.2(包括5.10.2)以前的。如果版本不一样,可以更新。

如果版本大于 5.10.2 ,无论是生成还是打印 PDF ,水印都是去不掉的。

FreeSpire.PDF是只能打印三页,而且生成的PDF不能超过十页。

 

操作PDF文档时,打印是常见的需求之一。

要将传过来的 json 生成 image 后,再把所有图片转成 PDF 并打印。

要求:

1、打印出来的图片大小要符合实际要求的大小

2、PDF 文件(test.pdf)的纸张大小就是图片大小

3、根据 json 传过来的打印机名字,可实现多台打印机打印

 

解决过程

1、生成的 image 是 System.Drawing.Image,要转化成 Spire.Pdf.Graphics.PdfImage

//Json生成的System.Drawing.Image image,Json中含所有所需打印机名字
image = printLayout.Draw();

ImageConverter imgconv = new ImageConverter();
byte[] bytes = (byte[])imgconv.ConvertTo(image, typeof(byte[]));
Stream stream = new MemoryStream(bytes);

Spire.Pdf.Graphics.PdfImage imagePdf = Spire.Pdf.Graphics.PdfImage.FromStream(stream);

 

2、换算打印图片大小,设置PDF纸张大小,去水印

复制代码
Spire.Pdf.PdfDocument newDocument = new Spire.Pdf.PdfDocument();
//删除第一页,破解水印
newDocument.Pages.Add();
newDocument.Pages.RemoveAt(0);

//根据实际需求,换算图片大小
float imageWidth = image.Width / 2.105f;
float imageHeight = image.Height / 2.105f;

//设置文档纸张尺寸
newDocument.PageSettings.Width = imageWidth;
newDocument.PageSettings.Height = imageHeight;
newDocument.PageSettings.Margins.All = 0;
复制代码

 

3、往PDF插入图片

Spire.Pdf.PdfPageBase newPage = newDocument.Pages.Add();
newPage.Canvas.DrawImage(imagePdf, 0, 0, imageWidth, imageHeight);

 

4、保存文件

pdfDocument.SaveToFile(fileName);

一定一定一定要先保存文件再打印!否则打印出来的第一页还是有水印。

不知道为啥,但是保存了就没有水印了

 

5、打印PDF(直接打印)

复制代码
        private void PrintPages(string printerName, Spire.Pdf.PdfDocument newDocument, int threadID, int timeout)
        {
            Thread thread = null;
            var task = Task.Run(() =>
            {
                thread = Thread.CurrentThread;
                try
                {
                    newDocument.PrintSettings.PrinterName = printerName;
                    //打印文档所有页面
                    newDocument.Print();
                    Log.Information($"[Thread {threadID}] Sent a printing request to printer {printerName} )");
                }
                catch (Exception ex)
                {
                    Log.Error($"[Thread {threadID}] Unable to send a printing request to printer {printerName}: {ex}");
                }
            });
            if (!task.Wait(timeout))
            {
                Log.Error($"[Thread {threadID}] Unable to send a printing request to printer {printerName}: Operation Timed Out!");
                thread.Abort();
            }
        }
复制代码

 

 

6、多台打印机打印

因为已经知道所有打印机名字,foreach取得每个打印机的名字,再调用上面打印的 function 就好。 

posted @   鱼仔鱼仔  阅读(1628)  评论(1编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示