Click here to Skip to main content
15,881,172 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
C#
byte[] bytes = System.IO.File.ReadAllBytes(@"C:\SGO3-1.pdf");
                               
           
       // MemoryStream outPDF = new MemoryStream();
            FileStream outPDF = new FileStream(@"C:\pdf1.pdf", FileMode.Create);
           // byte[] outBytes;
            PdfReader pdfr = new PdfReader(bytes);
            
                Document doc = new Document(PageSize.LETTER);
                
                    Document.Compress = true;
            
                    PdfWriter writer = PdfWriter.GetInstance(doc, outPDF);
                    
                    doc.Open();

                    PdfContentByte cb = writer.DirectContent;
                    cb.SaveState();

                    PdfImportedPage page;

                    for (int i = 1; i < pdfr.NumberOfPages + 1; i++)
                    {
                        page = writer.GetImportedPage(pdfr, i);
                        cb.AddTemplate(page, PageSize.LETTER.Width / pdfr.GetPageSize(i).Width, 0, 0, PageSize.LETTER.Height / pdfr.GetPageSize(i).Height, 0, 0);
                        doc.NewPage();
                        Console.WriteLine("creating pdf");
                    }


I am trying this another pdf file is being created.But while opening pdf it gives error message File is damaged or could not be repaired
Posted
Updated 31-Mar-15 1:58am
v2
Comments
John C Rayan 31-Mar-15 8:00am    
Are you able to open the document from your filesystem as normal?
Hitesh_Bhatt 31-Mar-15 8:06am    
original document which I am converting to byteArray is opening " SG03_1.pdf" plz check code.

1 solution

Use BinaryReader and BinaryWriter
example:
C#
Byte[] DocDataStream;

using (FileStream stream = File.Open(OriginalPDFFileName, FileMode.Open))
                    {
                        using (BinaryReader br = new BinaryReader(stream))
                        {
                            DocDataStream = br.ReadBytes((int)stream.Length);
                        }
                    }
// The PDF is now as Byte Array in memory

 using (var filestream = File.OpenWrite(NewPDFFileName))
            {
                BinaryWriter bw = new BinaryWriter(filestream);
                bw.Write(DocDataStream, 0, (int)DocDataStream.Length);
                bw.Close();
            }					
// And your file is rewritten!			
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900