Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ITextSharp将文本插入现有pdf_C#_Asp.net_Pdf_Itext_Pdf Generation - Fatal编程技术网

C# ITextSharp将文本插入现有pdf

C# ITextSharp将文本插入现有pdf,c#,asp.net,pdf,itext,pdf-generation,C#,Asp.net,Pdf,Itext,Pdf Generation,标题概括了这一切 我想添加一个文本到现有的PDF文件使用,但我找不到如何做它在任何地方在网上 注:我不能使用PDF格式。我找到了一种方法(不知道这是否是最好的,但它有效) 我希望这对某人有用=)(并在此处发布任何错误)这对我很有用,包括使用OutputStream: PdfReader reader = new PdfReader(new RandomAccessFileOrArray(Request.MapPath("Template.pdf")), null); Rectangle

标题概括了这一切

我想添加一个文本到现有的PDF文件使用,但我找不到如何做它在任何地方在网上

注:我不能使用PDF格式。

我找到了一种方法(不知道这是否是最好的,但它有效)


我希望这对某人有用=)(并在此处发布任何错误)

这对我很有用,包括使用OutputStream:

PdfReader reader = new PdfReader(new RandomAccessFileOrArray(Request.MapPath("Template.pdf")), null);
    Rectangle size = reader.GetPageSizeWithRotation(1);
    using (Stream outStream = Response.OutputStream)
    {
        Document document = new Document(size);
        PdfWriter writer = PdfWriter.GetInstance(document, outStream);

        document.Open();
        try
        {
            PdfContentByte cb = writer.DirectContent;

            cb.BeginText();
            try
            {
                cb.SetFontAndSize(BaseFont.CreateFont(), 12);
                cb.SetTextMatrix(110, 110);
                cb.ShowText("aaa");
            }
            finally
            {
                cb.EndText();
            }

                PdfImportedPage page = writer.GetImportedPage(reader, 1);
                cb.AddTemplate(page, 0, 0);

        }
        finally
        {
            document.Close();
            writer.Close();
            reader.Close();
        }
    }

除了上述出色的答案外,以下内容还显示了如何向多页文档的每页添加文本:

 using (var reader = new PdfReader(@"C:\Input.pdf"))
 {
    using (var fileStream = new FileStream(@"C:\Output.pdf", FileMode.Create, FileAccess.Write))
    {
       var document = new Document(reader.GetPageSizeWithRotation(1));
       var writer = PdfWriter.GetInstance(document, fileStream);

       document.Open();

       for (var i = 1; i <= reader.NumberOfPages; i++)
       {
          document.NewPage();

          var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
          var importedPage = writer.GetImportedPage(reader, i);

          var contentByte = writer.DirectContent;
          contentByte.BeginText();
          contentByte.SetFontAndSize(baseFont, 12);

          var multiLineString = "Hello,\r\nWorld!".Split('\n');

          foreach (var line in multiLineString)
          {
             contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, line, 200, 200, 0);
          }

          contentByte.EndText();
          contentByte.AddTemplate(importedPage, 0, 0);
       }

       document.Close();
       writer.Close();
    }
 }
使用(var reader=newpdfreader(@“C:\Input.pdf”))
{
使用(var fileStream=newfilestream(@“C:\Output.pdf”、FileMode.Create、FileAccess.Write))
{
var document=新文档(reader.GetPageSizeWithRotation(1));
var writer=PdfWriter.GetInstance(文档、文件流);
document.Open();

对于(var i=1;i这里有一种方法,它使用不同PDF客户端中显示的压模和绝对坐标(AdobeFoxIt等)


以下是一种在图像上打印的方法: 摘自。 为要放置在图像上的文本使用不同的层,并确保使用GetOverContent()方法

string oldFile=“FileWithImages.pdf”;
字符串watermarkedFile=“Layers.pdf”;
//在单独的层上创建水印
//创建iTextSharp.text.pdf.PdfReader对象以读取现有pdf文档
PdfReader reader1=新PdfReader(旧文件);
使用(FileStream fs=newfilestream(水印文件,FileMode.Create,FileAccess.Write,FileShare.None))
//创建iTextSharp.text.pdf.PdfStamper对象以将数据从iTextSharp.text.pdf.PdfReader对象写入FileStream对象
使用(PdfStamper压模=新PdfStamper(读取器1,fs))
{
//获取现有文档的总页数
int pageCount=reader1.NumberOfPages;
//为水印创建新层
PdfLayer层=新PdfLayer(“层”,stamp.Writer);
//循环浏览每一页

对于(int i=1;我喜欢一些随机的blabla-这类音乐让我耳目一新!我的oldfile.pdf包含2页,但newfile.pdf只包含oldfile.pdf的第一页。那么第二页在哪里呢???@Nurlan Kenzhebekov,为第二页添加以下代码:document.NewPage();PdfImportedPage page2=writer.GetImportedPage(reader,2);cb.AddTemplate(page2,0,0)//等下一页。@Tony S.不幸的是,这不会打印图像。您可能有解决方案吗?它可以工作,但我添加的文本放在现有pdf图像的下面。我如何修复此问题?旧pdf文件包含2页,但新生成的pdf只包含旧pdf文件的第一页。那么第二页在哪里呢AddTemplate部件应负责旋转,如果源文档中有旋转,请参阅哪个库中的“请求”和“响应”定位?响应是System.Web的一部分。它在Page类中。AddTemplate部分应负责旋转,如果源文档中有一个,请查看您对这些响应的引用类型。此部分实际上处理多个pages@Chris希弗豪尔:有没有一种方法可以把文本添加到一个特定的页面上文本仅限于我的PDF的最后一页。有什么想法吗?你能告诉我们如何使用参数“点”吗在你的方法中?编辑是有意义的,但删除了itextsharp标记,这就是我拒绝它的原因。但现在即使我添加了标记,它也会自动删除。它已与itext合并。虽然这段代码可能会解决这个问题,但如何以及为什么解决这个问题将真正有助于提高你文章的质量,并可能导致更多向上投票。请记住,你是在回答未来读者的问题,而不仅仅是现在提问的人。请在回答中添加解释,并说明适用的限制和假设。
 using (var reader = new PdfReader(@"C:\Input.pdf"))
 {
    using (var fileStream = new FileStream(@"C:\Output.pdf", FileMode.Create, FileAccess.Write))
    {
       var document = new Document(reader.GetPageSizeWithRotation(1));
       var writer = PdfWriter.GetInstance(document, fileStream);

       document.Open();

       for (var i = 1; i <= reader.NumberOfPages; i++)
       {
          document.NewPage();

          var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
          var importedPage = writer.GetImportedPage(reader, i);

          var contentByte = writer.DirectContent;
          contentByte.BeginText();
          contentByte.SetFontAndSize(baseFont, 12);

          var multiLineString = "Hello,\r\nWorld!".Split('\n');

          foreach (var line in multiLineString)
          {
             contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, line, 200, 200, 0);
          }

          contentByte.EndText();
          contentByte.AddTemplate(importedPage, 0, 0);
       }

       document.Close();
       writer.Close();
    }
 }
public static void AddTextToPdf(string inputPdfPath, string outputPdfPath, string textToAdd, System.Drawing.Point point)
    {
        //variables
        string pathin = inputPdfPath;
        string pathout = outputPdfPath;

        //create PdfReader object to read from the existing document
        using (PdfReader reader = new PdfReader(pathin))
        //create PdfStamper object to write to get the pages from reader 
        using (PdfStamper stamper = new PdfStamper(reader, new FileStream(pathout, FileMode.Create)))
        {
            //select two pages from the original document
            reader.SelectPages("1-2");

            //gettins the page size in order to substract from the iTextSharp coordinates
            var pageSize = reader.GetPageSize(1);

            // PdfContentByte from stamper to add content to the pages over the original content
            PdfContentByte pbover = stamper.GetOverContent(1);

            //add content to the page using ColumnText
            Font font = new Font();
            font.Size = 45;

            //setting up the X and Y coordinates of the document
            int x = point.X;
            int y = point.Y;

            y = (int) (pageSize.Height - y);

            ColumnText.ShowTextAligned(pbover, Element.ALIGN_CENTER, new Phrase(textToAdd, font), x, y, 0);
        }
    }
            string oldFile = "FileWithImages.pdf";
            string watermarkedFile = "Layers.pdf";
            // Creating watermark on a separate layer
            // Creating iTextSharp.text.pdf.PdfReader object to read the Existing PDF Document
            PdfReader reader1 = new PdfReader(oldFile);
            using (FileStream fs = new FileStream(watermarkedFile, FileMode.Create, FileAccess.Write, FileShare.None))
            // Creating iTextSharp.text.pdf.PdfStamper object to write Data from iTextSharp.text.pdf.PdfReader object to FileStream object
            using (PdfStamper stamper = new PdfStamper(reader1, fs))
            {
                // Getting total number of pages of the Existing Document
                int pageCount = reader1.NumberOfPages;

                // Create New Layer for Watermark
                PdfLayer layer = new PdfLayer("Layer", stamper.Writer);
                // Loop through each Page
                for (int i = 1; i <= pageCount; i++)
                {
                    // Getting the Page Size
                    Rectangle rect = reader1.GetPageSize(i);

                    // Get the ContentByte object
                    PdfContentByte cb = stamper.GetOverContent(i);

                    // Tell the cb that the next commands should be "bound" to this new layer
                    cb.BeginLayer(layer);
                    
                    BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                    cb.SetColorFill(BaseColor.RED);
                    cb.SetFontAndSize(bf, 100);

                    cb.BeginText();
                    cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Some random blablablabla...", rect.Width / 2, rect.Height / 2, - 90);
                    cb.EndText();

                    // Close the layer
                    cb.EndLayer();
                }
            }