Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7564383
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T13:53:25+00:00 2026-05-30T13:53:25+00:00

I would like to open an existing pdf, add some text and then output

  • 0

I would like to open an existing pdf, add some text and then output as content disposition using itext sharp. I have the following code. Where it falls down it is that i want to output as memory stream but need to filestream to open the original file.

Here’s what i have. Obviously defining PdfWriter twice won’t work.

   public static void Create(string path)
    {
        var Response = HttpContext.Current.Response;
        Response.Clear();
        Response.ContentType = "application/pdf";
        System.IO.MemoryStream m = new System.IO.MemoryStream();
        Document document = new Document();
        PdfWriter wri = PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create));
        PdfWriter.GetInstance(document, m);
        document.Open();
        document.Add(new Paragraph(DateTime.Now.ToString()));
        document.NewPage();
        document.Add(new Paragraph("Hello World"));
        document.Close();
        Response.OutputStream.Write(m.GetBuffer(), 0, m.GetBuffer().Length);
        Response.OutputStream.Flush();
        Response.OutputStream.Close();
        Response.End();
    } 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T13:53:26+00:00Added an answer on May 30, 2026 at 1:53 pm

    You’ve got a couple of problems that I’ll try to walk you through.

    First, the Document object is only for working with new PDFs, not modifying existing ones. Basically the Document object is a bunch of wrapper classes that abstract away the underlying parts of the PDF spec and allow you to work with higher level things like paragraphs and reflowable content. These abstractions turn what you think of “paragraphs” into raw commands that write the paragraph one line at a time with no relationship between lines. When working with an existing document there’s no safe way to say how to reflow text so these abstractions aren’t used.

    Instead you want to use the PdfStamper object. When working with this object you have two choices for how to work with potentially overlapping content, either your new text gets written on top of existing content or your text gets written below it. The two methods GetOverContent() or GetUnderContent() of an instantiated PdfStamper object will return a PdfContentByte object that you can then write text with.

    There’s two main ways to write text, either manually or through a ColumnText object. If you’ve done HTML you can think of the ColumnText object as using a big fixed-position single row, single column <TABLE>. The advantage of the ColumnText is that you can use the higher level abstractions such as Paragraph.

    Below is a full working C# 2010 WinForms app targeting iTextSharp 5.1.2.0 that show off the above. See the code comments for any questions. It should be pretty easy to convert this to ASP.Net.

    using System;
    using System.IO;
    using System.Windows.Forms;
    using iTextSharp.text;
    using iTextSharp.text.pdf;
    
    namespace WindowsFormsApplication1 {
        public partial class Form1 : Form {
            public Form1() {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e) {
                string existingFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "file1.pdf");
                string newFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "file2.pdf");
                using (FileStream fs = new FileStream(existingFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
                    using (Document doc = new Document(PageSize.LETTER)) {
                        using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) {
                            doc.Open();
    
                            doc.Add(new Paragraph("This is a test"));
    
                            doc.Close();
                        }
                    }
                }
    
                //Bind a PdfReader to our first document
                PdfReader reader = new PdfReader(existingFile);
                //Create a new stream for our output file (this could be a MemoryStream, too)
                using (FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
                    //Use a PdfStamper to bind our source file with our output file
                    using (PdfStamper stamper = new PdfStamper(reader, fs)) {
    
                        //In case of conflict we want our new text to be written "on top" of any existing content
                        //Get the "Over" state for page 1
                        PdfContentByte cb = stamper.GetOverContent(1);
    
                        //Begin text command
                        cb.BeginText();
                        //Set the font information
                        cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 16f);
                        //Position the cursor for drawing
                        cb.MoveText(50, 50);
                        //Write some text
                        cb.ShowText("This was added manually");
                        //End text command
                        cb.EndText();
    
                        //Create a new ColumnText object to write to
                        ColumnText ct = new ColumnText(cb);
                        //Create a single column who's lower left corner is at 100x100 and upper right is at 500x200
                        ct.SetSimpleColumn(100,100,500,200);
                        //Add a higher level object
                        ct.AddElement(new Paragraph("This was added using ColumnText"));
                        //Flush the text buffer
                        ct.Go();
    
                    }
                }
    
                this.Close();
            }
        }
    }
    

    As to your second problem about the FileStream vs MemoryStream, if you look at the method signature for almost every (actually all as far as I know) method within iTextSharp you’ll see that they all take a Stream object and not just a FileStream object. Any time you see this, even outside of iTextSharp, this means that you can pass in any subclass of Stream which includes the MemoryStream object, everything else stays the same.

    The code below is a slightly modified version of the one above. I’ve removed most of the comments to make it shorter. The main change is that we’re using a MemoryStream instead of a FileStream. Also, when we’re done with the PDF when need to close the PdfStamper object before accessing the raw binary data. (The using statment will do this for us automatically later but it also closes the stream so we need to manually do it here.)

    One other thing, never, ever use the GetBuffer() method of the MemoryStream. It sounds like what you want (and I have mistakenly used it, too) but instead you want to use ToArray(). GetBuffer() includes uninitialized bytes which usually produces corrupt PDFs. Also, instead of writing to the HTTP Response stream I’m saving the bytes to array first. From a debugging perspective this allows me to finish all of my iTextSharp and System.IO code and make sure that it is correct, then do whatever I want with the raw byte array. In my case I don’t have a web server handy so I’m writing them to disk but you could just as easily call Response.BinaryWrite(bytes)

    string existingFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "file1.pdf");
    string newFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "file2.pdf");
    PdfReader reader = new PdfReader(existingFile);
    byte[] bytes;
    using(MemoryStream ms = new MemoryStream()){
        using (PdfStamper stamper = new PdfStamper(reader, ms)) {
            PdfContentByte cb = stamper.GetOverContent(1);
            ColumnText ct = new ColumnText(cb);
            ct.SetSimpleColumn(100,100,500,200);
            ct.AddElement(new Paragraph("This was added using ColumnText"));
            ct.Go();
    
            //Flush the PdfStamper's buffer
            stamper.Close();
            //Get the raw bytes of the PDF
            bytes = ms.ToArray();
        }
    }
    
    //Do whatever you want with the bytes
    //Below I'm writing them to disk but you could also write them to the output buffer, too
    using (FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
        fs.Write(bytes, 0, bytes.Length);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Using ActiveX - FileSystemObject I would like to: - Open an existing file -
I would like to open a popup window using javascript in my c#.net app.
I would like to open 2 url's using open $url = 'http://xtreme-jumps.eu/demos.txt'; $url2 =
I would like to open a file using open file dialog. If the opened
I would like to open an existing Visual Studio project in Visual Studio, so
I would like to open into memory an existing .sln file. Example of a
i have a code generator project i would like to offer like open source,
I would like to open a new aspx page when i click on a
I would like to open an OleDbConnection to an Excel file that's in memory
I would like to open a document after my ASP.NET page loads in a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.