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

Add Uploaded File(s) to iTextSharp PDF New Page

我正处于完成 pdf 生成器的最后一步。我正在使用 iText sharp,并且在 Whosebug 的帮助下,我能够毫无问题地标记 base64 图像。

我的问题是如何遍历已发布的文件并添加一个包含已发布图像文件的新页面。这是我目前标记图像的方式......但是,它来自 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);

//stamping base64 图像非常完美 - 现在我需要在 stamper 关闭之前将上传的图像标记到同一文档中的新页面上。

        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 />

基本步骤:

  • 迭代 HttpFileCollection
  • 将每个 HttpPostedFile 读入字节数组。
  • 在上一步中使用字节数组创建 iText 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);
    }
}