首页 > 编程语言 >C# 批量打印图片,Image转PDF并可多台打印机打印(Spire.PDF、去水印)

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

时间:2022-12-15 15:47:23浏览次数:42  
标签:C# newDocument 打印 Spire Pdf PDF image

版本:一定要是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、打印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();
            }
        }

 

 

5、多台打印机打印

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

标签:C#,newDocument,打印,Spire,Pdf,PDF,image
From: https://www.cnblogs.com/fishanan/p/16985149.html

相关文章