Click here to Skip to main content
14,734,056 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
Hi,
Below is a function I use to generate receipt on a pdf file. I want to save many receipts on one pdf file and cut into singles later. I have a javascript function -dowloadFileJS- that shows the receipt for download. My method is, I read the existing pdf file and convert it into bytes. Then I combine the bytes whith the newly generated receipt byte. Then replace with the combined bytes. The problem is,it always replace the content of the pdf with just the current receipt file but does not append the new receipt to the old ones. Please help.


  FileStream fs = new FileStream(Server.MapPath("Images/report.pdf"), FileMode.Open, FileAccess.Read);
                MemoryStream ms = new MemoryStream();
                fs.CopyTo(ms);
                byte[] realbytes = Combine(ms.ToArray(), bytes);
                ms.Close();
                fs.Close();

                using (FileStream file = new FileStream(Server.MapPath("Images/report.pdf"), FileMode.Append, System.IO.FileAccess.Write))
                {
                    file.Write(realbytes, 0, realbytes.Length);

                }
                string path = "Images/report.pdf";
                ScriptManager.RegisterClientScriptBlock(this, GetType(), "none", "<script>dowloadFileJS(\'" + path + "\','This done successfully');</script>", false);



//script
function dowloadFileJS(path, message) {
       if (message != '')
           alert(message); // Place your Message Here
       var iframe = document.createElement("iframe");
       iframe.src = "UqDownload.aspx?fileT=" + path + "";
       iframe.style.display = "none";
       document.body.appendChild(iframe);
   }
//end of script - script tags messing up code formatting here.




public byte[] Combine(byte[] a1, byte[] a2)
    {
        byte[] ret = new byte[a1.Length + a2.Length];
        Array.Copy(a1, 0, ret, 0, a1.Length);
        Array.Copy(a2, 0, ret, a1.Length, a2.Length);
        return ret;
    }


 
protected void GenerateReportfirstyear()
        {
            DateTime now = DateTime.Now;
            //DataRow dr = GetData("SELECT * FROM StudBillLog where ExamID = '" + TextBox1.Text + "'").Rows[0]; ;
            Document document = new Document(PageSize.A4, 88f, 88f, 10f, 10f);
            Font NormalFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, Color.BLACK);
            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
                PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
                Phrase phrase = null;
                PdfPCell cell = null;
                PdfPTable table = null;
                Color color = null;
                Color colorn = null;

                document.Open();

                //Header Table
                table = new PdfPTable(2);
                table.TotalWidth = 500f;
                table.LockedWidth = true;
                table.SetWidths(new float[] { 0.3f, 0.7f });

                //Company Logo

                cell = ImageCell("~/rex/pic.jpg", 30f, PdfPCell.ALIGN_CENTER);
                table.AddCell(cell);

                colorn = new Color(System.Drawing.ColorTranslator.FromHtml("#009900"));
                phrase = new Phrase();
                phrase.Add(new Chunk("College of Education \r\n", FontFactory.GetFont("TIMES_ROMAN", 11, Font.BOLD, colorn)));
                phrase.Add(new Chunk("FINANCE DIVISION \r\n\n", FontFactory.GetFont("TIMES_ROMAN", 8, Font.BOLD, Color.BLACK)));
               

                phrase.Add(new Chunk("OFFICIAL RECEIPT\r\n", FontFactory.GetFont("TIMES_ROMAN", 10, Font.BOLD, Color.BLACK)));

                cell = PhraseCell(phrase, PdfPCell.ALIGN_LEFT);
                cell.VerticalAlignment = PdfCell.ALIGN_TOP;
                table.AddCell(cell);

                //Separater Line
                color = new Color(System.Drawing.ColorTranslator.FromHtml("#A9A9A9"));
                DrawLine(writer, 25f, document.Top - 79f, document.PageSize.Width - 25f, document.Top - 79f, color);
                DrawLine(writer, 25f, document.Top - 80f, document.PageSize.Width - 25f, document.Top - 80f, color);
                document.Add(table);


                table = new PdfPTable(2);
                table.SetWidths(new float[] { 0.5f, 2f });
                table.TotalWidth = 340f;
                table.LockedWidth = true;
                table.SpacingBefore = 20f;
                table.HorizontalAlignment = Element.ALIGN_LEFT;

                //Employee Id
                table.AddCell(PhraseCell(new Phrase("Received From:", FontFactory.GetFont("Arial", 8, Font.BOLD, Color.BLACK)), PdfPCell.ALIGN_LEFT));
                table.AddCell(PhraseCell(new Phrase("" + this.txtNameFirstYear.Text, FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)), PdfPCell.ALIGN_LEFT));
                cell = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
                cell.Colspan = 2;
                cell.PaddingBottom = 10f;
                table.AddCell(cell);

                table.AddCell(PhraseCell(new Phrase("ExamID:", FontFactory.GetFont("Arial", 8, Font.BOLD, Color.BLACK)), PdfPCell.ALIGN_LEFT));
                table.AddCell(PhraseCell(new Phrase("" + this.cboExamNoFirstYear.Text, FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)), PdfPCell.ALIGN_LEFT));
                cell = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
                cell.Colspan = 2;
                cell.PaddingBottom = 10f;
                table.AddCell(cell);

                NumberToEnglish numToeng = new NumberToEnglish();
                string numfirst = numToeng.changeCurrencyToWords(firstyearcurrency);


               

               

                table.AddCell(PhraseCell(new Phrase("Program :", FontFactory.GetFont("Arial", 8, Font.BOLD, Color.BLACK)), PdfPCell.ALIGN_LEFT));
                table.AddCell(PhraseCell(new Phrase("" + Prog, FontFactory.GetFont("Arial", 8, Font.NORMAL, Color.BLACK)), PdfPCell.ALIGN_LEFT));
                cell = PhraseCell(new Phrase(), PdfPCell.ALIGN_CENTER);
                cell.Colspan = 2;
                cell.PaddingBottom = 10f;
                table.AddCell(cell);            

               document.Add(table);
               document.Close();
               bytesfirstyear = memoryStream.ToArray();
               memoryStream.Close();              
            }
        }
        private static void DrawLine(PdfWriter writer, float x1, float y1, float x2, float y2, Color color)
        {
            PdfContentByte contentByte = writer.DirectContent;
            contentByte.SetColorStroke(color);
            contentByte.MoveTo(x1, y1);
            contentByte.LineTo(x2, y2);
            contentByte.Stroke();
        }
        private static PdfPCell PhraseCell(Phrase phrase, int align)
        {
            PdfPCell cell = new PdfPCell(phrase);
            cell.BorderColor = Color.WHITE;
            cell.VerticalAlignment = PdfCell.ALIGN_TOP;
            cell.HorizontalAlignment = align;
            cell.PaddingBottom = 2f;
            cell.PaddingTop = 0f;
            return cell;
        }
        private static PdfPCell ImageCell(string path, float scale, int align)
        {
            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath(path));
            image.ScalePercent(scale);
            PdfPCell cell = new PdfPCell(image);
            cell.BorderColor = Color.WHITE;
            cell.VerticalAlignment = PdfCell.ALIGN_TOP;
            cell.HorizontalAlignment = align;
            cell.PaddingBottom = 0f;
            cell.PaddingTop = 0f;
            return cell;
        }
Posted
Updated 3-Sep-15 3:10am
v2
Comments
Maciej Los 3-Sep-15 8:42am
   
Why to open file twice: once for read and second for write (append mode)?

1 solution

Please, read my comment to the question.

Here is an idea:
public static void AppendMyBytes(string path, byte[] bytes)
{
    //argument-checking here.

    using (var stream = new FileStream(path, FileMode.Append))
    {
        stream.Write(bytes, 0, bytes.Length);
    }
}


Note: if Append mode is used then...
MSDN wrote:
Opens the file if it exists and seeks to the end of the file, or creates a new file. This requires FileIOPermissionAccess.Append permission. FileMode.Append can be used only in conjunction with FileAccess.Write. Trying to seek to a position before the end of the file throws an IOException exception, and any attempt to read fails and throws a NotSupportedException exception
.

For further information, please see: FileMode Enumeration[^]
   
v2
Comments
Member 10820603 3-Sep-15 9:06am
   
I get this error "could not find a part of the path"
path is

string path = "Images/report.pdf";
Maciej Los 3-Sep-15 9:23am
   
Server.MapPath("filetopath")
Member 10820603 3-Sep-15 10:08am
   
System.Web.HttpContext.Current.Server.MapPath works perfectly but does not append. It replaces rather
[no name] 3-Sep-15 12:35pm
   
Colorado vs Hawaii Live

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