ItextSharp return a corrupted file after editing existing pdf file











up vote
0
down vote

favorite












I am new to itextSharp. What I am doing is just editing the old file and instead of saving the new file on the server I just want it to download at the time. but unfortunately after editing the file and being downloaded, file display a message cannot open the file. It may be corrupted.



Here is my code.



public FileStreamResult export( int ? id)
{
string pathin = Server.MapPath(Url.Content("~/PDF/input.pdf"));


PdfReader reader = new PdfReader(pathin);
iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);
Document document = new Document(size);

// open the writer
//FileStream ms = new FileStream(pathout, FileMode.Create, FileAccess.Write);
var ms = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, ms);
writer.CloseStream = false;
document.Open();

// the pdf content
PdfContentByte cb = writer.DirectContent;

// select the font properties
BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
cb.SetColorFill(BaseColor.DARK_GRAY);
cb.SetFontAndSize(bf, 18f);

// write the text in the pdf content
cb.BeginText();
string text = "this is text";
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 500, 500, 0);
cb.EndText();
cb.BeginText();
text = "this is my post";
// put the alignment and coordinates here
cb.ShowTextAligned(1, text, 600, 400, 0);
cb.EndText();

// create the new page and add it to the pdf
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);


ms.Position = 0;
document.Close();
//ms.Close();

writer.Close();
reader.Close();


return File(ms, "application/pdf","test.pdf");
}


Any help will be really appreciated. :)










share|improve this question


























    up vote
    0
    down vote

    favorite












    I am new to itextSharp. What I am doing is just editing the old file and instead of saving the new file on the server I just want it to download at the time. but unfortunately after editing the file and being downloaded, file display a message cannot open the file. It may be corrupted.



    Here is my code.



    public FileStreamResult export( int ? id)
    {
    string pathin = Server.MapPath(Url.Content("~/PDF/input.pdf"));


    PdfReader reader = new PdfReader(pathin);
    iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);
    Document document = new Document(size);

    // open the writer
    //FileStream ms = new FileStream(pathout, FileMode.Create, FileAccess.Write);
    var ms = new MemoryStream();
    PdfWriter writer = PdfWriter.GetInstance(document, ms);
    writer.CloseStream = false;
    document.Open();

    // the pdf content
    PdfContentByte cb = writer.DirectContent;

    // select the font properties
    BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    cb.SetColorFill(BaseColor.DARK_GRAY);
    cb.SetFontAndSize(bf, 18f);

    // write the text in the pdf content
    cb.BeginText();
    string text = "this is text";
    // put the alignment and coordinates here
    cb.ShowTextAligned(1, text, 500, 500, 0);
    cb.EndText();
    cb.BeginText();
    text = "this is my post";
    // put the alignment and coordinates here
    cb.ShowTextAligned(1, text, 600, 400, 0);
    cb.EndText();

    // create the new page and add it to the pdf
    PdfImportedPage page = writer.GetImportedPage(reader, 1);
    cb.AddTemplate(page, 0, 0);


    ms.Position = 0;
    document.Close();
    //ms.Close();

    writer.Close();
    reader.Close();


    return File(ms, "application/pdf","test.pdf");
    }


    Any help will be really appreciated. :)










    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I am new to itextSharp. What I am doing is just editing the old file and instead of saving the new file on the server I just want it to download at the time. but unfortunately after editing the file and being downloaded, file display a message cannot open the file. It may be corrupted.



      Here is my code.



      public FileStreamResult export( int ? id)
      {
      string pathin = Server.MapPath(Url.Content("~/PDF/input.pdf"));


      PdfReader reader = new PdfReader(pathin);
      iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);
      Document document = new Document(size);

      // open the writer
      //FileStream ms = new FileStream(pathout, FileMode.Create, FileAccess.Write);
      var ms = new MemoryStream();
      PdfWriter writer = PdfWriter.GetInstance(document, ms);
      writer.CloseStream = false;
      document.Open();

      // the pdf content
      PdfContentByte cb = writer.DirectContent;

      // select the font properties
      BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
      cb.SetColorFill(BaseColor.DARK_GRAY);
      cb.SetFontAndSize(bf, 18f);

      // write the text in the pdf content
      cb.BeginText();
      string text = "this is text";
      // put the alignment and coordinates here
      cb.ShowTextAligned(1, text, 500, 500, 0);
      cb.EndText();
      cb.BeginText();
      text = "this is my post";
      // put the alignment and coordinates here
      cb.ShowTextAligned(1, text, 600, 400, 0);
      cb.EndText();

      // create the new page and add it to the pdf
      PdfImportedPage page = writer.GetImportedPage(reader, 1);
      cb.AddTemplate(page, 0, 0);


      ms.Position = 0;
      document.Close();
      //ms.Close();

      writer.Close();
      reader.Close();


      return File(ms, "application/pdf","test.pdf");
      }


      Any help will be really appreciated. :)










      share|improve this question













      I am new to itextSharp. What I am doing is just editing the old file and instead of saving the new file on the server I just want it to download at the time. but unfortunately after editing the file and being downloaded, file display a message cannot open the file. It may be corrupted.



      Here is my code.



      public FileStreamResult export( int ? id)
      {
      string pathin = Server.MapPath(Url.Content("~/PDF/input.pdf"));


      PdfReader reader = new PdfReader(pathin);
      iTextSharp.text.Rectangle size = reader.GetPageSizeWithRotation(1);
      Document document = new Document(size);

      // open the writer
      //FileStream ms = new FileStream(pathout, FileMode.Create, FileAccess.Write);
      var ms = new MemoryStream();
      PdfWriter writer = PdfWriter.GetInstance(document, ms);
      writer.CloseStream = false;
      document.Open();

      // the pdf content
      PdfContentByte cb = writer.DirectContent;

      // select the font properties
      BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
      cb.SetColorFill(BaseColor.DARK_GRAY);
      cb.SetFontAndSize(bf, 18f);

      // write the text in the pdf content
      cb.BeginText();
      string text = "this is text";
      // put the alignment and coordinates here
      cb.ShowTextAligned(1, text, 500, 500, 0);
      cb.EndText();
      cb.BeginText();
      text = "this is my post";
      // put the alignment and coordinates here
      cb.ShowTextAligned(1, text, 600, 400, 0);
      cb.EndText();

      // create the new page and add it to the pdf
      PdfImportedPage page = writer.GetImportedPage(reader, 1);
      cb.AddTemplate(page, 0, 0);


      ms.Position = 0;
      document.Close();
      //ms.Close();

      writer.Close();
      reader.Close();


      return File(ms, "application/pdf","test.pdf");
      }


      Any help will be really appreciated. :)







      c# .net model-view-controller itext






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 10 at 16:03









      zaid khan

      397




      397
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          You change the position of the memory stream before closing the document:



              ms.Position = 0;
          document.Close();


          As the trailer of the pdf in the result stream is written during the closing of the document, your change of stream position causes the pdf trailer to be written over the pdf header and the stream position thereafter to not be at the start.



          Instead first close the document and the reader (the writer implicitly is closed by closing the document) and reset the stream position thereafter:



              document.Close();
          reader.Close();

          ms.Position = 0;
          return File(ms, "application/pdf","test.pdf");





          share|improve this answer























          • yeah. thank you. Now i am thinking how can i miss this point. Great man!
            – zaid khan
            Nov 11 at 10:05











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53240767%2fitextsharp-return-a-corrupted-file-after-editing-existing-pdf-file%23new-answer', 'question_page');
          }
          );

          Post as a guest
































          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          0
          down vote



          accepted










          You change the position of the memory stream before closing the document:



              ms.Position = 0;
          document.Close();


          As the trailer of the pdf in the result stream is written during the closing of the document, your change of stream position causes the pdf trailer to be written over the pdf header and the stream position thereafter to not be at the start.



          Instead first close the document and the reader (the writer implicitly is closed by closing the document) and reset the stream position thereafter:



              document.Close();
          reader.Close();

          ms.Position = 0;
          return File(ms, "application/pdf","test.pdf");





          share|improve this answer























          • yeah. thank you. Now i am thinking how can i miss this point. Great man!
            – zaid khan
            Nov 11 at 10:05















          up vote
          0
          down vote



          accepted










          You change the position of the memory stream before closing the document:



              ms.Position = 0;
          document.Close();


          As the trailer of the pdf in the result stream is written during the closing of the document, your change of stream position causes the pdf trailer to be written over the pdf header and the stream position thereafter to not be at the start.



          Instead first close the document and the reader (the writer implicitly is closed by closing the document) and reset the stream position thereafter:



              document.Close();
          reader.Close();

          ms.Position = 0;
          return File(ms, "application/pdf","test.pdf");





          share|improve this answer























          • yeah. thank you. Now i am thinking how can i miss this point. Great man!
            – zaid khan
            Nov 11 at 10:05













          up vote
          0
          down vote



          accepted







          up vote
          0
          down vote



          accepted






          You change the position of the memory stream before closing the document:



              ms.Position = 0;
          document.Close();


          As the trailer of the pdf in the result stream is written during the closing of the document, your change of stream position causes the pdf trailer to be written over the pdf header and the stream position thereafter to not be at the start.



          Instead first close the document and the reader (the writer implicitly is closed by closing the document) and reset the stream position thereafter:



              document.Close();
          reader.Close();

          ms.Position = 0;
          return File(ms, "application/pdf","test.pdf");





          share|improve this answer














          You change the position of the memory stream before closing the document:



              ms.Position = 0;
          document.Close();


          As the trailer of the pdf in the result stream is written during the closing of the document, your change of stream position causes the pdf trailer to be written over the pdf header and the stream position thereafter to not be at the start.



          Instead first close the document and the reader (the writer implicitly is closed by closing the document) and reset the stream position thereafter:



              document.Close();
          reader.Close();

          ms.Position = 0;
          return File(ms, "application/pdf","test.pdf");






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 11 at 12:19

























          answered Nov 10 at 18:46









          mkl

          51.6k1165141




          51.6k1165141












          • yeah. thank you. Now i am thinking how can i miss this point. Great man!
            – zaid khan
            Nov 11 at 10:05


















          • yeah. thank you. Now i am thinking how can i miss this point. Great man!
            – zaid khan
            Nov 11 at 10:05
















          yeah. thank you. Now i am thinking how can i miss this point. Great man!
          – zaid khan
          Nov 11 at 10:05




          yeah. thank you. Now i am thinking how can i miss this point. Great man!
          – zaid khan
          Nov 11 at 10:05


















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53240767%2fitextsharp-return-a-corrupted-file-after-editing-existing-pdf-file%23new-answer', 'question_page');
          }
          );

          Post as a guest




















































































          Popular posts from this blog

          Xamarin.iOS Cant Deploy on Iphone

          Glorious Revolution

          Dulmage-Mendelsohn matrix decomposition in Python