0

我正在使用PDFium c#工具从 PNG 图像流创建 PDF 文档。

我有一个获取多个图像流对象的 API,我应该组合图像流并创建 PDF 文档和 PDF 流。我需要使用另一个 API 来保存此文档。

我浏览了PDFium 文档,但是这些示例显示了如何从图像加载 PDF,而不是从流加载

我们是否需要从 Stream 创建图像来加载 PDF 或者是否有其他替代方法?

非常感谢任何帮助

先感谢您

我根据文档创建的示例代码

public void GeneratePdfFromImageStream(List<Stream> imageStreams, String pdfSaveLocation = null)
    {
        int pageIndex = 0;
        //Initialize C# PDF Library
        PdfCommon.Initialize();
        //Create a PDF document
        using (var doc = PdfDocument.CreateNew())
        {

            foreach (var imageStream in imageStreams)
            {

                //I am creating a Bitmap image here, is there a way I can achevie the same withrout creating the image 
                 var image = System.Drawing.Bitmap.FromStream(imageStream, true) as System.Drawing.Bitmap;

                //Create empty PdfBitmap
                using (PdfBitmap pdfBitmap = new PdfBitmap(image.Width, image.Height, true))
                {
                    using (var g = System.Drawing.Graphics.FromImage(pdfBitmap.Image))
                    {
                        //Draw image to PdfBitmap
                        g.DrawImage(image, 0, 0, image.Width, image.Height);
                    }
                    //Create Image object
                    var imageObject = PdfImageObject.Create(doc, pdfBitmap, 0, 0);
                    //Calculate size of image in PDF points
                    var size = CalculateSize(pdfBitmap.Width, pdfBitmap.Height, image.HorizontalResolution, image.VerticalResolution);
                    //Add empty page to PDF document
                    doc.Pages.InsertPageAt(pageIndex, size);
                    //Insert image to newly created page
                    doc.Pages[pageIndex].PageObjects.Add(imageObject);
                    //set image matrix
                    imageObject.Matrix = new FS_MATRIX(size.Width, 0, 0, size.Height, 0, 0);
                    //Generate PDF page content to content stream
                    doc.Pages[pageIndex].GenerateContent();
                    pageIndex++;
                }
            }
            // Save  PDF document as "saved.pdf" in no incremental mode
            if (string.IsNullOrWhiteSpace(pdfSaveLocation))
                doc.Save($"saved_{Guid.NewGuid().ToString()}.pdf", SaveFlags.NoIncremental);
        }

    }
4

0 回答 0