如何编写附加已存在的pdf文件 [英] How to write to append an already existing pdf file

查看:53
本文介绍了如何编写附加已存在的pdf文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



以下是我用来在pdf文件上生成收据的功能。我想在一个pdf文件上保存很多收据,然后再剪成单曲。我有一个javascript函数-dowloadFileJS-显示下载的收据。我的方法是,我读取现有的pdf文件并将其转换为字节。然后我组合新生成的收据字节的字节。然后用组合字节替换。问题是,它总是只用当前收据文件替换pdf的内容,但不会将新收据附加到旧收据。请帮忙。





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;
        }

推荐答案

请阅读我对该问题的评论。



以下是一个想法:

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写道:

打开文件(如果存在)并寻找文件的末尾,或者创建一个新文件。这需要FileIOPermissionAccess.Append权限。 FileMode.Append只能与FileAccess.Write一起使用。尝试在文件结束之前寻找位置会抛出IOException异常,并且任何读取尝试都会失败并抛出NotSupportedException异常

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更多信息,请参阅: FileMode枚举 [ ^ ]


这篇关于如何编写附加已存在的pdf文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆