将上传的文件添加到iTextSharp PDF新页面

本文关键字:iTextSharp PDF 新页面 添加 文件 | 更新日期: 2023-09-27 17:50:17

现在是完成pdf生成器的最后一步。我正在使用iText锐利,我能够盖章base64图像没有问题,这要归功于StackOverflow的帮助。

我的问题是我如何迭代发布的文件,并在其上添加一个带有发布图像文件的新页面。这是我现在打印图像的方法…然而,它来自base64。我需要添加从我的应用程序中选择的上传图像到pdf最好,而邮票是打开的。就是没法让我的代码工作。

我觉得这很容易迭代,但不能得到逻辑。请帮助:

        PdfContentByte pdfContentByte = stamper.GetOverContent(1);
        PdfContentByte pdfContentByte2 = stamper.GetOverContent(4);
        var image = iTextSharp.text.Image.GetInstance(
            Convert.FromBase64String(match.Groups["data"].Value)
        );
        image.SetAbsolutePosition(270, 90);
        image.ScaleToFit(250f, 100f);
        pdfContentByte.AddImage(image);

//冲压base64图像工作完美-现在我需要在印章关闭之前将上传的图像盖戳到同一文档的新页面上。

        var imagepath = "//test//";
        HttpFileCollection uploadFilCol = HttpContext.Current.Request.Files;
        for (int i = 0; i < uploadFilCol.Count; i++)
        {
            HttpPostedFile file = uploadFilCol[i];
            using (FileStream fs = new FileStream(imagepath +  "Invoice-" +
            HttpContext.Current.Request.Form.Get("genUUID") + file, FileMode.Open))
            {
                HttpPostedFile file = uploadFilCol[i];
                pdfContentByte2.AddImage(file);
            }
        }

我发布的文件来自于一个html页面的输入表单

<input type="file" id="file" name="files[]" runat="server" multiple />

将上传的文件添加到iTextSharp PDF新页面

基本步骤:
  • 遍历HttpFileCollection
  • 将每个HttpPostedFile读入字节数组。
  • 用字节数组创建ittext Image
  • 设置图像的绝对位置,并可根据需要缩放。
  • 添加GetOverContent()指定页码的图像

一个快速的片段,让您开始。已测试,并假设您已经设置了PdfReaderStreamPdfStamper,以及一个工作文件上传:

HttpFileCollection uploadFilCol = HttpContext.Current.Request.Files;
for (int i = 0; i < uploadFilCol.Count; i++)
{
    HttpPostedFile postedFile = uploadFilCol[i];
    using (var br = new BinaryReader(postedFile.InputStream))
    {
        var imageBytes = br.ReadBytes(postedFile.ContentLength);
        var image = Image.GetInstance(imageBytes);
        // still not sure if you want to add a new blank page, but 
        // here's how
        //stamper.InsertPage(
        //    APPEND_NEW_PAGE_NUMBER, reader.GetPageSize(APPEND_NEW_PAGE_NUMBER - 1)
        //);
        // image absolute position
        image.SetAbsolutePosition(absoluteX, absoluteY);
        // scale image if needed
        // image.ScaleAbsolute(...);
        // PAGE_NUMBER => add image to specific page number
        stamper.GetOverContent(PAGE_NUMBER).AddImage(image);
    }
}