简体   繁体   中英

Can't copy PDF File from MemoryStream to FileStream

Am i doing anything wrong? May i ask why can't i open both pdfs file saved?

As for MemoryStream it is saved to my directory -> Downloads Folder from Chrome and for FileStream it is saved to the FilePath i specified in my codes.

Appreciate any help please. Thank you.

Codes:

protected void BTN_Assign_Click(object sender, EventArgs e)
    {
        //String id = DDL_PatientID.SelectedItem.ToString();
        String id = TB_PatientID.Text;
        String name = TB_PatientName.Text;
        String bedID = DDL_BedID.SelectedItem.ToString();
        String classType = DDL_Class.SelectedItem.ToString();
        String block = TB_Block.Text;
        String level = TB_Level.Text;
        String staffId = DDL_StaffID.SelectedItem.ToString();
        DateTime dt = DateTime.Now;
        String dtAssign = dt.ToString("dd MMM yyyy h:mm tt");

        int result = 0;

        //Assigning bed (In Beds Table)
        /*BedsBLL add = new BedsBLL();
        result = add.assignBed(bedID, id, name, classType, block, level, staffId, dtAssign);*/

        //Updating status of Bed Selected (In BedsList Table)
        String status = "Alloted";
        BedsBLL update = new BedsBLL();
        result = update.updateBedStatusToAlloted(status, bedID, id, name, staffId, dtAssign);

        AdmissionBLL a = new AdmissionBLL();
        int assignCounter = 0;
        assignCounter = a.updateBedAssignedAdmission(id, bedID);

        //PDF Creation with Admission Details from previous page
        // --- START ---

        DataTable admissionDetails = new DataTable();
        admissionDetails.Columns.Add("Date & Time Admitted");
        admissionDetails.Columns.Add("Reason");
        admissionDetails.Columns.Add("Family Phone");
        admissionDetails.Columns.Add("Family Email");
        admissionDetails.Columns.Add("First Time Admitted");

        DataRow dr;
        dr = admissionDetails.NewRow();
        dr["Date & Time Admitted"] = Session["DTAdmitted"].ToString();
        dr["Reason"] = Session["Reason"].ToString();
        dr["Family Phone"] = Session["FamilyPhone"].ToString();
        dr["Family Email"] = Session["FamilyEmail"].ToString();
        dr["First Time Admitted"] = Session["FirstTimeAdmitted"].ToString();
        admissionDetails.Rows.Add(dr);

        Document pdfDocument = new Document(PageSize.A4, 40f, 40f, 40f, 40f);
        Font NormalFont = FontFactory.GetFont("Arial", 8, Font.NORMAL, BaseColor.BLACK);
        Font BoldFontForHeader = FontFactory.GetFont("Arial", 10, Font.BOLD, BaseColor.BLACK);

        String fileName = @"C:\Users\Dom\Downloads\WebFormApplication\WebFormApplication\WebFormApplication\Exported Documents\" + Session["PatientID"].ToString() + " Admission PDF" + ".pdf";

        Directory.CreateDirectory(Path.GetDirectoryName(fileName));

        PdfPCell cell = null;

        using (MemoryStream ms = new MemoryStream())
        {
            PdfWriter writer = PdfWriter.GetInstance(pdfDocument, ms);

            FileStream fs = new FileStream(fileName, FileMode.Create);

            //Admission Record
            PdfPTable admissionTable = new PdfPTable(admissionDetails.Columns.Count);
            admissionTable.TotalWidth = 550f;
            admissionTable.LockedWidth = true;
            admissionTable.HorizontalAlignment = Element.ALIGN_CENTER;
            admissionTable.SetWidths(new float[] { 0.35f, 0.35f, 0.35f, 0.35f, 0.35f });
            admissionTable.SpacingBefore = 30f;

            string[] headersName = { "Date Time Admitted", "Reason", "Family Phone", "Family Email", "First Time Admitted" };

            for (int i = 0; i < headersName.Length; i++)
            {
                PdfPCell hCell = new PdfPCell(new Phrase(headersName[i].ToString(), BoldFontForHeader));
                admissionTable.AddCell(hCell);
            }

            foreach (DataRow row in admissionDetails.Rows)
            {
                foreach (object tableCell in row.ItemArray)
                {
                    cell = new PdfPCell(new Phrase(tableCell.ToString()));
                    cell.Padding = 5;
                    admissionTable.AddCell(cell);
                }
            }

            //Beds Record
            PdfPTable bedsRecord = new PdfPTable(5);
            bedsRecord.TotalWidth = 550f;
            bedsRecord.LockedWidth = true;
            bedsRecord.HorizontalAlignment = Element.ALIGN_CENTER;
            bedsRecord.SetWidths(new float[] { 0.35f, 0.35f, 0.35f, 0.35f, 0.35f });
            bedsRecord.SpacingBefore = 30f;

            string[] headersNameBed = { "Bed ID", "Class", "Block", "Level", "Staff Incharge ID" };

            for (int i = 0; i < headersNameBed.Length; i++)
            {
                PdfPCell hCell = new PdfPCell(new Phrase(headersNameBed[i].ToString(), BoldFontForHeader));
                bedsRecord.AddCell(hCell);
            }

            PdfPCell[] cells = new PdfPCell[] {
                new PdfPCell(new Phrase(bedID.ToString())),
                new PdfPCell(new Phrase(classType.ToString())),
                new PdfPCell(new Phrase(block.ToString())),
                new PdfPCell(new Phrase(level.ToString())),
                new PdfPCell(new Phrase(staffId.ToString()))
            };

            PdfPRow bRow = new PdfPRow(cells);
            bedsRecord.Rows.Add(bRow);

            pdfDocument.Open();

            //Top of Document

            Paragraph p1 = new Paragraph("Mount Olympus Hospital", new Font(Font.FontFamily.HELVETICA, 18));
            Paragraph p2 = new Paragraph("24 Jalan Kapal Street 42 Singapore 554524", new Font(Font.FontFamily.HELVETICA, 12));
            Paragraph p3 = new Paragraph("Telephone: 6550-9514 Fax: 6550-9245", new Font(Font.FontFamily.HELVETICA, 12));

            p1.Alignment = Element.ALIGN_CENTER;
            p2.Alignment = Element.ALIGN_CENTER;
            p3.Alignment = Element.ALIGN_CENTER;

            pdfDocument.Add(p1);
            pdfDocument.Add(p2);
            pdfDocument.Add(p3);

            Paragraph p4 = new Paragraph("Patient ID: " + Session["PatientID"], new Font(Font.FontFamily.TIMES_ROMAN, 11));
            Paragraph p5 = new Paragraph("Patient Name: " + Session["PatientName"], new Font(Font.FontFamily.TIMES_ROMAN, 11));

            p4.SpacingBefore = 20f;
            p4.Alignment = Element.ALIGN_LEFT;
            p5.Alignment = Element.ALIGN_LEFT;
            p5.SpacingAfter = 20f;

            pdfDocument.Add(p4);
            pdfDocument.Add(p5);

            Paragraph p6 = new Paragraph("Admission Details", new Font(Font.FontFamily.HELVETICA, 16));
            p6.Alignment = Element.ALIGN_LEFT;
            p6.SpacingBefore = 20f;

            pdfDocument.Add(p6);

            pdfDocument.Add(admissionTable);

            Paragraph p7 = new Paragraph("Bed Details", new Font(Font.FontFamily.HELVETICA, 16));
            p7.Alignment = Element.ALIGN_LEFT;
            p7.SpacingBefore = 20f;

            pdfDocument.Add(p7);

            pdfDocument.Add(bedsRecord);

            byte[] bytes = ms.ToArray();
            ms.Position = 0;
            ms.CopyTo(fs);
            fs.CopyTo(ms);

            pdfDocument.Close();



            ms.Close();
            fs.Close();
            Response.Clear();
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=" + Session["PatientID"].ToString() + " Admission PDF" + ".pdf");
            Response.ContentType = "application/pdf";
            Response.Buffer = true;
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.BinaryWrite(bytes);
            Response.End();
            Response.Close();
        }

        /*using (System.IO.FileStream fs = new System.IO.FileStream())
        {

        }*/



        // --- END ---

        //Showing succcesful panel.
        if (result > 0 && assignCounter > 0)
        {
            Panel_ErrorMsg.Visible = true;
            //Panel_ErrorMsg.ToolTip = "Click on the button to return to Beds List";
            lb_ErrorMsg.Text = "Successfully assigned bed to Patient " + name 
                + " and updated Bed " + bedID + " status to Alloted.";
            BTN_Assign.Visible = false;
        }
    }

Try putting the .Close() before the .CopyTo():

        pdfDocument.Close();

        ms.Position = 0;
        ms.CopyTo(fs);

I got it working to save in both locations...

Default Downloads Folder by Chrome and specified folder.

The edited codes:

                pdfDocument.Close();
                //ms.Position = 0;
                //ms.CopyTo(fs);
                //fs.CopyTo(ms);

                byte[] bytes = ms.ToArray();

                using (FileStream fs = new FileStream(fileName, FileMode.Create))
                {
                    ms.Position = 0;
                    ms.CopyTo(fs);
                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM