Open() публичный Метод

Opens the document.
Once the document is opened, you can't write any Header- or Meta-information anymore. You have to open the document before you can begin to add content to the body of the document.
public Open ( ) : void
Результат void
Пример #1
0
        public override void SaveFileAs(string fileName, FileType type)
        {
            // step 1: creation of a document-object
            iTextSharp.text.Document myDocument = new iTextSharp.text.Document(PageSize.A4.Rotate());
            try
            {
                // step 2:
                // Now create a writer that listens to this doucment and writes the document to desired Stream.
                PdfWriter.GetInstance(myDocument, new FileStream(fileName, FileMode.CreateNew));

                // step 3:  Open the document now using
                myDocument.Open();

                // step 4: Now add some contents to the document
                myDocument.Add(new iTextSharp.text.Paragraph(parsedFile.contentRaw));
            }
            catch (iTextSharp.text.DocumentException de)
            {
                Console.Error.WriteLine(de.Message);
            }
            catch (IOException ioe)
            {
                Console.Error.WriteLine(ioe.Message);
            }
            myDocument.Close();
        }
Пример #2
0
        public FileStreamResult ExportarPDF()
        {
            var     autores  = db.Autores.Include(a => a.Pais);
            WebGrid grid     = new WebGrid(source: autores, canPage: false, canSort: false);
            string  gridHtml = grid.GetHtml(
                columns: grid.Columns
                (
                    grid.Column("ID", header: "Codigo"),
                    grid.Column("Apellido", header: "Apellido"),
                    grid.Column("Nombre", header: "Nombre"),
                    grid.Column("Nacionalidad", header: "CodPais"),
                    grid.Column("Pais.Descripcion", header: "Pais"),
                    grid.Column("FechaNacimiento", header: "Fecha Nacimiento", format: (item) => string.Format("{0:dd/MM/yyyy}", item.FechaNacimiento))
                )
                ).ToString();
            string exportData = String.Format("<html><head>{0}</head><body>{1}</body></html>", "<p>Lista de Autores</p> <style>table{ border-spacing: 10px; border-collapse: separate; }</style>", gridHtml);
            var    bytes      = System.Text.Encoding.UTF8.GetBytes(exportData);

            using (var input = new MemoryStream(bytes))
            {
                var output   = new MemoryStream();
                var document = new iTextSharp.text.Document(PageSize.A4, 50, 50, 50, 50);
                var writer   = PdfWriter.GetInstance(document, output);
                writer.CloseStream = false;
                document.Open();
                var xmlWorker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
                xmlWorker.ParseXHtml(writer, document, input, System.Text.Encoding.UTF8);
                document.Close();
                output.Position = 0;
                return(new FileStreamResult(output, "application/pdf"));
            }
        }
Пример #3
0
        //Alım Geçmişi Pdf Rapor Butonu
        private void PdfButton_Click(object sender, EventArgs e)
        {
            iTextSharp.text.Document pdfDosya = new iTextSharp.text.Document();

            PdfWriter.GetInstance(pdfDosya, new FileStream("D:Rapor.pdf", FileMode.Create));
            pdfDosya.Open();
            pdfDosya.AddCreator("Swap - Modern Dünyada Tarıma Dair Alışveriş");
            pdfDosya.AddAuthor("Kullanıcı");
            pdfDosya.AddTitle("SATIN ALMA RAPORU");

            SqlCommand     komut = new SqlCommand("Select * From AlimKayitTablosu Where Tarih BETWEEN @t1 and @t2 and KullaniciID=" + Login.UserId, baglanti.baglanti());
            SqlDataAdapter data  = new SqlDataAdapter(komut);

            data.SelectCommand.Parameters.AddWithValue("@t1", StartDatePicker.Value);
            data.SelectCommand.Parameters.AddWithValue("@t2", EndDatePicker.Value);
            SqlDataReader oku = komut.ExecuteReader();

            string id, tarih, miktar, alimtutar, komisyon, metin;

            metin = "KullaniciID / Tarih / Miktar / AlimTutari / UygulamaKomsiyon \n";
            pdfDosya.Add(new Paragraph(metin));
            while (oku.Read())
            {
                id        = Convert.ToString(oku["KullaniciID"]);
                tarih     = Convert.ToString(oku["Tarih"]);
                miktar    = Convert.ToString(oku["Miktar"]);
                alimtutar = Convert.ToString(oku["AlimTutari"]);
                komisyon  = Convert.ToString(oku["UygulamaKomisyonu"]);
                metin     = id + "  -  " + tarih + "  -  " + miktar + "  -  " + alimtutar + "  -  " + komisyon + "\n";
                pdfDosya.Add(new Paragraph(metin));
            }
            pdfDosya.Close();
            baglanti.baglanti().Close();
        }
Пример #4
0
        public void FillDocument(byte[] docArray, iTextSharp.text.Document document)
        {
            //byte[] all;

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

                //document.SetPageSize (PageSize.LETTER);
                document.Open();
                PdfContentByte  cb = writer.DirectContent;
                PdfImportedPage page;

                PdfReader reader;
                //foreach (byte[] p in docArray) {
                reader = new PdfReader(docArray);
                int pages = reader.NumberOfPages;

                // loop over document pages
                for (int i = 1; i <= pages; i++)
                {
                    //document.SetPageSize (PageSize.LETTER);
                    document.NewPage();
                    page = writer.GetImportedPage(reader, i);
                    cb.AddTemplate(page, 0, 0);
                }
                //}
            }
        }
Пример #5
0
        /// <summary>
        /// 图片转换PDF jpg,jpeg,png,tif,tiff
        /// </summary>
        /// <param name="imgfile">图片名称,包含路径</param>
        /// <param name="newPdfFile">pdf文件路径</param>
        /// <returns>返回转换成功后的PDF文件名称</returns>
        public static bool ImageConvertPdf(string imgfile, string newPdfFile, out string errorMsg)
        {
            try {
                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imgfile);
                float percentage            = 1;
                float resizedWidht          = image.Width;
                float resizedHeight         = image.Height;

                while (resizedWidht > (image.Width - 36 - 36) * 0.8)
                {
                    percentage    = percentage * 0.9f;
                    resizedHeight = image.Height * percentage;
                    resizedWidht  = image.Width * percentage;
                }
                while (resizedHeight > (image.Height - 36 - 36) * 0.8)
                {
                    percentage    = percentage * 0.9f;
                    resizedHeight = image.Height * percentage;
                    resizedWidht  = image.Width * percentage;
                }
                image.ScalePercent(percentage * 100);
                iTextSharp.text.Rectangle rec = new iTextSharp.text.Rectangle(resizedWidht, resizedHeight);
                using (iTextSharp.text.Document doc = new iTextSharp.text.Document(rec)) {
                    PdfWriter write = PdfWriter.GetInstance(doc, new FileStream(newPdfFile, FileMode.Create));
                    doc.Open();
                    doc.Add(image);
                }
                errorMsg = string.Empty;
                return(true);
            } catch (Exception ex) {
                errorMsg = ex.Message;
                return(false);
            }
        }
Пример #6
0
        public Document CreatePdfDocument(Chart chart, string path)
        {
            RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
                (int) chart.ActualWidth,
                (int) chart.ActualHeight,
                96d,
                96d,
                PixelFormats.Pbgra32);

            renderBitmap.Render(chart);

            MemoryStream stream = new MemoryStream();
            BitmapEncoder encoder = new BmpBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
            encoder.Save(stream);

            Bitmap bitmap = new Bitmap(stream);
            System.Drawing.Image image = bitmap;

            System.Drawing.Image resizedImage = ResizeImage(image, image.Width*2, image.Height);

            Document doc = new Document(PageSize.A4);
            PdfWriter.GetInstance(doc, new FileStream(path, FileMode.OpenOrCreate));
            doc.Open();
            Image pdfImage = Image.GetInstance(resizedImage, ImageFormat.Jpeg);
            doc.Add(pdfImage);
            doc.Close();
            
            return doc;
        }
Пример #7
0
 private void button2_Click(object sender, EventArgs e)
 {
     BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
     iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 12, iTextSharp.text.Font.ITALIC, BaseColor.DARK_GRAY);
     Document doc = new Document(iTextSharp.text.PageSize.LETTER,10,10,42,42);
     PdfWriter pdw = PdfWriter.GetInstance(doc, new FileStream(naziv + ".pdf", FileMode.Create));
     doc.Open();
     Paragraph p = new Paragraph("Word Count for : "+naziv,times);
     doc.Add(p);
     p.Alignment = 1;
     PdfPTable pdt = new PdfPTable(2);
     pdt.HorizontalAlignment = 1;
     pdt.SpacingBefore = 20f;
     pdt.SpacingAfter = 20f;
     pdt.AddCell("Word");
     pdt.AddCell("No of repetitions");
     foreach (Rijec r in lista_rijeci)
     {
         pdt.AddCell(r.Tekst);
         pdt.AddCell(Convert.ToString(r.Ponavljanje));
     }
     using (MemoryStream stream = new MemoryStream())
     {
         chart1.SaveImage(stream, ChartImageFormat.Png);
         iTextSharp.text.Image chartImage = iTextSharp.text.Image.GetInstance(stream.GetBuffer());
         chartImage.ScalePercent(75f);
         chartImage.Alignment = 1;
         doc.Add(chartImage);
     }
     doc.Add(pdt);
     doc.Close();
     MessageBox.Show("PDF created!");
 }
Пример #8
0
    public void HTMLToPdf(string htmlText)
    {
        iTextSharpText.Document oDocument = new iTextSharpText.Document(iTextSharpText.PageSize.A4, 10, 10, 10, 0);
        System.IO.MemoryStream  mStream   = new System.IO.MemoryStream();
        PdfWriter writer = PdfWriter.GetInstance(oDocument, mStream);

        oDocument.Open();

        using (var htmlMS = new MemoryStream(System.Text.Encoding.Default.GetBytes(htmlText)))
        {
            //Create a stream to read our CSS..

            string css = File.ReadAllText(Server.MapPath(@"~\App_Themes\\Estilos\\CertificadoADP.css"));
            using (var cssMS = new MemoryStream(System.Text.Encoding.Default.GetBytes(css)))
            {
                //Get an instance of the generic XMLWorker
                XMLWorkerHelper xmlWorker = XMLWorkerHelper.GetInstance();

                //Parse our HTML using everything setup above
                xmlWorker.ParseXHtml(writer, oDocument, htmlMS, cssMS, System.Text.Encoding.Default);
            }
        }

        oDocument.Close();
        ShowPdf("CertificadoADP_" + persona.PersonaCuip.cuip, mStream);
    }
Пример #9
0
 protected void btnPDF_Click(object sender, ImageClickEventArgs e)
 {
     Response.ContentType = "application/pdf";
     Response.AddHeader("content-disposition", "attachment;filename=UserDetails.pdf");
     Response.Cache.SetCacheability(HttpCacheability.NoCache);
     var sw = new StringWriter();
     var hw = new HtmlTextWriter(sw);
     gvdetails.AllowPaging = false;
     gvdetails.DataBind();
     gvdetails.RenderControl(hw);
     gvdetails.HeaderRow.Style.Add("width", "15%");
     gvdetails.HeaderRow.Style.Add("font-size", "10px");
     gvdetails.Style.Add("text-decoration", "none");
     gvdetails.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
     gvdetails.Style.Add("font-size", "8px");
     var sr = new StringReader(sw.ToString());
     var pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);
     var htmlparser = new HTMLWorker(pdfDoc);
     PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
     pdfDoc.Open();
     htmlparser.Parse(sr);
     pdfDoc.Close();
     Response.Write(pdfDoc);
     Response.End();
 }
Пример #10
0
// ---------------------------------------------------------------------------    
    /**
     * Creates a PDF document.
     */
    public byte[] CreatePdf() {
      using (MemoryStream ms = new MemoryStream()) { 
        using (var c =  AdoDB.Provider.CreateConnection()) {
          c.ConnectionString = AdoDB.CS;
          c.Open();
          // step 1
          using (Document document = new Document(PageSize.A5)) {
            // step 2
            PdfWriter writer = PdfWriter.GetInstance(document, ms);
            // step 3
            document.Open();
            // step 4
            int[] start = new int[3];
            for (int i = 0; i < 3; i++) {
              start[i] = writer.PageNumber;
              AddParagraphs(document, c, SQL[i], FIELD[i]);
              document.NewPage();
            }
            PdfPageLabels labels = new PdfPageLabels();
            labels.AddPageLabel(start[0], PdfPageLabels.UPPERCASE_LETTERS);
            labels.AddPageLabel(start[1], PdfPageLabels.DECIMAL_ARABIC_NUMERALS);
            labels.AddPageLabel(
              start[2], PdfPageLabels.DECIMAL_ARABIC_NUMERALS, 
              "Movies-", start[2] - start[1] + 1
            );
            writer.PageLabels = labels;
          }
          return ms.ToArray();
        }
      }
    }
Пример #11
0
        protected void btnExportPDF_Click(object sender, EventArgs e)
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=Student.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter   sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);

            GridView1.AllowPaging = false;
            HtmlForm frm = new HtmlForm();

            GridView1.Parent.Controls.Add(frm);
            frm.Attributes["runat"] = "server";
            frm.Controls.Add(GridView1);
            frm.RenderControl(hw);
            GridView1.DataBind();
            StringReader sr = new StringReader(sw.ToString());

            iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(PageSize.A4, 10f, 10f, 10f, 0f);
            HTMLWorker htmlparser           = new HTMLWorker(pdfDoc);

            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.Write(pdfDoc);
            Response.End();
        }
Пример #12
0
        public string CreatePDFLang(string folder, Lang lang)
        {
            iTextSharp.text.Document doc = new iTextSharp.text.Document();
            string path = Path.Combine(folder, Guid.NewGuid().ToString() + ".pdf");

            doc.SetMargins(0f, 0f, 2f, 0f);
            PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create));
            //Открываем документ
            doc.Open();
            BaseFont baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Font font  = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.NORMAL);
            PdfPTable            table = new PdfPTable(1);
            PdfPCell             cell  = new PdfPCell(new Phrase("Код " + lang.name, font));

            cell.Colspan             = 0;
            cell.HorizontalAlignment = 1;
            cell.Border = 0;
            table.AddCell(cell);
            doc.Add(table);
            table                    = new PdfPTable(1);
            cell                     = new PdfPCell(new Phrase(lang.text, font));
            cell.Colspan             = 0;
            cell.HorizontalAlignment = 0;
            cell.Border              = 0;
            table.AddCell(cell);
            doc.Add(table);
            doc.Close();
            return(path);
        }
Пример #13
0
        public FileStreamResult BaoCaoSanPham()
        {
            var     sp       = db.SanPhams.Where(s => s.BiXoa == 0).ToList <SanPham>();
            WebGrid gird     = new WebGrid(source: sp, canPage: false, canSort: false);
            string  girdHtml = gird.GetHtml(
                columns: gird.Columns(
                    gird.Column("MaSanPham", "STT"),
                    gird.Column("TenSanPham", "Tên"),
                    gird.Column("SoLuongTon", "SL")
                    )
                ).ToString();
            string exportData = string.Format("<html><head><meta charset=" + "utf - 8" + "/>{0}</head><body>{1}</body></html>", "<style>table{border-spacing:10px; border-collapse:separate;}</style>", girdHtml);
            var    bytes      = System.Text.Encoding.UTF8.GetBytes(exportData);

            using (var input = new MemoryStream(bytes))
            {
                var output   = new MemoryStream();
                var document = new iTextSharp.text.Document(PageSize.A4, 50, 50, 50, 50);
                var writer   = PdfWriter.GetInstance(document, output);
                writer.CloseStream = false;

                document.Open();

                var xmlWorker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
                xmlWorker.ParseXHtml(writer, document, input, System.Text.Encoding.UTF8);
                document.Close();
                output.Position = 0;
                return(new FileStreamResult(output, "application/pdf"));
            }
        }
Пример #14
0
        public void Save(System.Drawing.Bitmap bm, string filename, System.Drawing.RotateFlipType rotate)
        {
            Bitmap image = bm;

            if (rotate != RotateFlipType.RotateNoneFlipNone)
            {
                image.RotateFlip(rotate);
            }

            using (FileStream stream = new FileStream(filename, FileMode.Create))
            {
                using (iTextSharp.text.Document pdfDocument = new iTextSharp.text.Document(PageSize.LETTER, PAGE_LEFT_MARGIN, PAGE_RIGHT_MARGIN, PAGE_TOP_MARGIN, PAGE_BOTTOM_MARGIN))
                {
                    iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDocument, stream);
                    pdfDocument.Open();

                    MemoryStream ms = new MemoryStream();
                    image.Save(ms, System.Drawing.Imaging.ImageFormat.Tiff);
                    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(ms);
                    img.ScaleToFit(PageSize.LETTER.Width - (PAGE_LEFT_MARGIN + PAGE_RIGHT_MARGIN), PageSize.LETTER.Height - (PAGE_TOP_MARGIN + PAGE_BOTTOM_MARGIN));
                    pdfDocument.Add(img);

                    pdfDocument.Close();
                    writer.Close();
                }
            }
        }
Пример #15
0
        public string CreatePDFList(string folder, List <Lang> langs)
        {
            iTextSharp.text.Document doc = new iTextSharp.text.Document();
            string path = Path.Combine(folder, Guid.NewGuid().ToString() + ".pdf");

            doc.SetMargins(0f, 0f, 2f, 0f);
            PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create));
            //Открываем документ
            doc.Open();
            BaseFont baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\arial.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Font font  = new iTextSharp.text.Font(baseFont, iTextSharp.text.Font.DEFAULTSIZE, iTextSharp.text.Font.NORMAL);
            PdfPTable            table = new PdfPTable(1);
            PdfPCell             cell  = new PdfPCell(new Phrase("Конвертирование языков программирования", font));

            cell.Colspan             = 0;
            cell.HorizontalAlignment = 1;
            cell.Border = 0;
            table.AddCell(cell);
            doc.Add(table);
            PdfPTable ctable = new PdfPTable(4);

            for (int j = 0; j < langs.Count; j++)
            {
                AddHeaderCell(ctable, langs[j].name, font);
            }
            for (int j = 0; j < langs.Count; j++)
            {
                AddTextCell(ctable, langs[j].text, font);
            }
            doc.Add(ctable);
            doc.Close();
            return(path);
        }
Пример #16
0
        public string CreatePdfFromImages(ClassificationPdfRequest PdfRequest)
        {
            this.OutputFolder     = ConfigurationManager.AppSettings["OutputFiles"].ToString();
            this.ImagesFolderPath = Path.Combine(OutputFolder, PdfRequest.BatchName, "Images");
            string DestinationPdfFolder = Path.Combine(OutputFolder, PdfRequest.BatchName, "ManualPDF");
            string RandomFileName       = Path.GetRandomFileName() + ".pdf";
            string DestinationPdfFile   = Path.Combine(DestinationPdfFolder, RandomFileName);

            if (!Directory.Exists(DestinationPdfFolder))
            {
                Directory.CreateDirectory(DestinationPdfFolder);
            }

            iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(0, 0, 2481, 3508);
            using (var ms = new MemoryStream())
            {
                var document = new iTextSharp.text.Document(pageSize, 0, 0, 0, 0);
                iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms).SetFullCompression();
                document.Open();
                foreach (string Image in PdfRequest.Images)
                {
                    string SourceImage   = Path.Combine(ImagesFolderPath, Image);
                    var    ImageInstance = iTextSharp.text.Image.GetInstance(SourceImage);
                    ImageInstance.ScaleToFit(document.PageSize.Width, document.PageSize.Height);
                    document.Add(ImageInstance);
                }
                document.Close();
                File.WriteAllBytes(DestinationPdfFile, ms.ToArray());
            }
            //byte[] ms= CreatePdf(ImagesFolderPath);
            return(Path.Combine(PdfRequest.BatchName, "ManualPDF", RandomFileName));
        }
Пример #17
0
 private void button3_Click(object sender, EventArgs e)
 {
     using (SaveFileDialog sfd = new SaveFileDialog()
     {
         Filter = "PDF file|*.pdf", ValidateNames = true
     })
     {
         if (sfd.ShowDialog() == DialogResult.OK)
         {
             iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.LETTER);
             {
                 try
                 {
                     PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.Create));
                     doc.Open();
                     doc.Add(new iTextSharp.text.Paragraph(label2.Text + "\n" + label3.Text + "\n" + "\n" + "\n" + label4.Text + "\n" + label5.Text + "\n" + "\n" + "\n" + label6.Text + "\n" + label7.Text + "\n" + "\n" + "\n" + label8.Text + "\n" + label9.Text + "\n" + "\n" + "\n" + label10.Text + "\n" + label11.Text + "\n" + "\n" + "\n" + label12.Text + "\n" + richTextBox1.Text));
                 }
                 catch (Exception ex)
                 {
                     MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                 }
                 finally
                 {
                     doc.Close();
                 }
             }
         }
     }
 }
Пример #18
0
        private void ExportDataTableToPdf(DataTable queryList, String url, String v2, Control control)
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition",
                               "attachment;filename=" + v2 + ".pdf");

            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            iTextSharp.text.Document document = new iTextSharp.text.Document();
            document.SetPageSize(iTextSharp.text.PageSize.A4);
            PdfWriter.GetInstance(document, Response.OutputStream);
            document.Open();

            //Table Data
            PdfPTable table = new PdfPTable(queryList.Columns.Count);

            for (int i = 0; i < queryList.Rows.Count; i++)
            {
                for (int j = 0; j < queryList.Columns.Count; j++)
                {
                    table.AddCell(queryList.Rows[i][j].ToString());
                }
            }

            document.Add(table);

            document.Close();

            Response.Write(document);

            Response.End();
        }
Пример #19
0
    protected void ExportPDF(GridView gv, iTextSharp.text.Document newDoc)
    {
        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter hw = new HtmlTextWriter(sw))
            {
                gv.RenderControl(hw);
                gv.AllowPaging = false;
                gv.DataBind();


                StringReader sr = new StringReader(sw.ToString());

                HTMLWorker htmlParse = new HTMLWorker(newDoc);
                PdfWriter  writer    = PdfWriter.GetInstance(newDoc, Response.OutputStream);
                newDoc.Open();
                htmlParse.Parse(sr);
                newDoc.Close();
                Response.Write(newDoc);


                Response.End();
                gv.AllowPaging = true;
                gv.DataBind();
            }
        }
    }
Пример #20
0
        public FileStreamResult GetPdf1()
        {
            var html   = GetHtml();
            var css    = GetCss();
            var bytes  = System.Text.Encoding.UTF8.GetBytes(html);
            var bytes1 = System.Text.Encoding.UTF8.GetBytes(css);
            var output = new MemoryStream();

            using (var input = new MemoryStream(bytes))
            {
                var input1 = new MemoryStream(bytes1);
                // this MemoryStream is closed by FileStreamResult

                var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4_LANDSCAPE, 50, 50, 50, 50);
                var writer   = PdfWriter.GetInstance(document, output);
                writer.CloseStream = false;
                document.Open();

                var xmlWorker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();

                xmlWorker.ParseXHtml(writer, document, input, input1);
                document.Close();
                output.Position = 0;
            }
            return(new FileStreamResult(output, "application/pdf"));
        }
Пример #21
0
        public void Go()
        {
            var outputFile = Helpers.IO.GetClassOutputPath(this);
            var fixedHtml = FixBrokenServerControlMarkup(HTML);
            using (FileStream stream = new FileStream(
                outputFile,
                FileMode.Create,
                FileAccess.Write))
            {
                using (var document = new Document())
                {
                    PdfWriter writer = PdfWriter.GetInstance(
                        document, stream
                    );
                    document.Open();
                    using (var xmlSnippet = new StringReader(fixedHtml))
                    {
                        XMLWorkerHelper.GetInstance().ParseXHtml(
                            writer, document, xmlSnippet
                        );
                    }

                }
            }
        }
Пример #22
0
// ---------------------------------------------------------------------------
    public void Write(Stream stream) {
      // use one of the previous examples to create a PDF
      MovieTemplates mt = new MovieTemplates();
      // Create a reader
      byte[] pdf = Utility.PdfBytes(mt);
      PdfReader reader = new PdfReader(pdf);
      // loop over all the pages in the original PDF
      int n = reader.NumberOfPages;      
      using (ZipFile zip = new ZipFile()) {
        for (int i = 0; i < n; ) {
          string dest = string.Format(RESULT, ++i);
          using (MemoryStream ms = new MemoryStream()) {
// We'll create as many new PDFs as there are pages
            // step 1
            using (Document document = new Document()) {
              // step 2
              using (PdfCopy copy = new PdfCopy(document, ms)) {
                // step 3
                document.Open();
                // step 4
                copy.AddPage(copy.GetImportedPage(reader, i));
              }
            }
            zip.AddEntry(dest, ms.ToArray());
          }
        }
        zip.AddEntry(Utility.ResultFileName(mt.ToString() + ".pdf"), pdf);
        zip.Save(stream);       
      }
    }
Пример #23
0
// ===========================================================================
    public void Write(Stream stream) {
      // step 1
      using (Document document = new Document(PageSize.POSTCARD, 30, 30, 30, 30)) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        writer.CompressionLevel = 0;
        // step 3
        document.Open();
        // step 4
        Image img = Image.GetInstance(Path.Combine(
          Utility.ResourceImage, "loa.jpg"
        ));
        img.SetAbsolutePosition(
          (PageSize.POSTCARD.Width - img.ScaledWidth) / 2,
          (PageSize.POSTCARD.Height - img.ScaledHeight) / 2
        );
        writer.DirectContent.AddImage(img);
        Paragraph p = new Paragraph(
          "Foobar Film Festival", 
          new Font(Font.FontFamily.HELVETICA, 22)
        );
        p.Alignment = Element.ALIGN_CENTER;
        document.Add(p);        
      }
    }
Пример #24
0
// ---------------------------------------------------------------------------
/*
 * you DO NOT want to use classes within the System.Drawing namespace to
 * manipulate image files in ASP.NET applications, see the warning here:
 * http://msdn.microsoft.com/en-us/library/system.drawing.aspx
*/
    public byte[] CreatePdf(long quality) {
      using (MemoryStream msDoc = new MemoryStream()) {
        Image img = null;
        using (System.Drawing.Bitmap dotnetImg = 
            new System.Drawing.Bitmap(RESOURCE)) 
        {
          // set codec to jpeg type => jpeg index codec is "1"
          System.Drawing.Imaging.ImageCodecInfo codec = 
          System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
          // set parameters for image quality
          System.Drawing.Imaging.EncoderParameters eParams = 
            new System.Drawing.Imaging.EncoderParameters(1);
          eParams.Param[0] = 
            new System.Drawing.Imaging.EncoderParameter(
              System.Drawing.Imaging.Encoder.Quality, quality
          );
          using (MemoryStream msImg = new MemoryStream()) {
            dotnetImg.Save(msImg, codec, eParams);
            msImg.Position = 0;
            img = Image.GetInstance(msImg);
            img.SetAbsolutePosition(15, 15);
            // step 1
            using (Document document = new Document()) {
              // step 2
              PdfWriter.GetInstance(document, msDoc);
              // step 3
              document.Open();
              // step 4
              document.Add(img);
            }
          }
        }
        return msDoc.ToArray();
      }
    }
 // ===========================================================================
 public void Write(Stream stream)
 {
     // step 1
     using (Document document = new Document())
     {
         // step 2
         PdfWriter.GetInstance(document, stream);
         document.SetPageSize(PageSize.A5);
         document.SetMargins(36, 72, 108, 180);
         document.SetMarginMirroring(true);
         // step 3
         document.Open();
         // step 4
         document.Add(new Paragraph(
           "The left margin of this odd page is 36pt (0.5 inch); " +
           "the right margin 72pt (1 inch); " +
           "the top margin 108pt (1.5 inch); " +
           "the bottom margin 180pt (2.5 inch).")
         );
         Paragraph paragraph = new Paragraph();
         paragraph.Alignment = Element.ALIGN_JUSTIFIED;
         for (int i = 0; i < 20; i++)
         {
             paragraph.Add("Hello World! Hello People! " +
             "Hello Sky! Hello Sun! Hello Moon! Hello Stars!"
             );
         }
         document.Add(paragraph);
         document.Add(new Paragraph(
           "The right margin of this even page is 36pt (0.5 inch); " +
           "the left margin 72pt (1 inch).")
         );
     }
 }
Пример #26
0
 public static void GeneratePdfSingleDataType(string filePath, string title, string content)
 {
     try
     {
         Logger.LogI("GeneratePDF -> " + filePath);
         var doc = new Document(PageSize.A3, 36, 72, 72, 144);
         using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
         {
             PdfWriter.GetInstance(doc, fs);
             doc.Open();
             doc.AddTitle(title);
             doc.AddAuthor(Environment.MachineName);
             doc.Add(
                 new Paragraph("Title : " + title + Environment.NewLine + "ServerName : " +
                               Environment.MachineName +
                               Environment.NewLine + "Author : " + Environment.UserName));
             doc.NewPage();
             doc.Add(new Paragraph(content));
             doc.Close();
         }
     }
     catch (Exception ex)
     {
         Logger.LogE(ex.Source + " -> " + ex.Message + "\n" + ex.StackTrace);
     }
 }
Пример #27
0
 // ---------------------------------------------------------------------------
 public void Write(Stream stream)
 {
     // Use old example to create PDF
     MovieTemplates mt = new MovieTemplates();
     byte[] pdf = Utility.PdfBytes(mt);
     using (ZipFile zip = new ZipFile())
     {
         using (MemoryStream ms = new MemoryStream())
         {
             // step 1
             using (Document document = new Document())
             {
                 // step 2
                 PdfWriter writer = PdfWriter.GetInstance(document, ms);
                 // step 3
                 document.Open();
                 // step 4
                 PdfPTable table = new PdfPTable(2);
                 PdfReader reader = new PdfReader(pdf);
                 int n = reader.NumberOfPages;
                 PdfImportedPage page;
                 for (int i = 1; i <= n; i++)
                 {
                     page = writer.GetImportedPage(reader, i);
                     table.AddCell(Image.GetInstance(page));
                 }
                 document.Add(table);
             }
             zip.AddEntry(RESULT, ms.ToArray());
         }
         zip.AddEntry(Utility.ResultFileName(mt.ToString() + ".pdf"), pdf);
         zip.Save(stream);
     }
 }
        private void ExportToPDF()
        {
            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter hw = new HtmlTextWriter(sw))
                {
                    //To Export all pages
                    this.gvExportToPdf.AllowPaging = false;
                    //this.BindGridView();

                    this.gvExportToPdf.RenderControl(hw);
                    StringReader sr = new StringReader(sw.ToString());
                    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
                    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

                    Response.ContentType = "application/pdf";
                    Response.AddHeader("content-disposition", "attachment;filename=DashboardReport.pdf");
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                    pdfDoc.Open();
                    htmlparser.Parse(sr);
                    pdfDoc.Close();
                    Response.Write(pdfDoc);
                    Response.End();
                }
            }
        }
 private void InitializeDocument()
 {
     MemoryStream baos = new MemoryStream();
     document = new Document();
     writer = PdfWriter.GetInstance(document, baos);
     document.Open();
 }
        protected override void MakePdf(string outPdf) {
            Document doc = new Document(PageSize.A4.Rotate());
            PdfWriter pdfWriter = PdfWriter.GetInstance(doc, new FileStream(outPdf, FileMode.Create));
            doc.SetMargins(45, 45, 0, 100);
            doc.Open();


            CssFilesImpl cssFiles = new CssFilesImpl();
            cssFiles.Add(
                XMLWorkerHelper.GetCSS(
                    File.OpenRead(RESOURCES + Path.DirectorySeparatorChar + testPath + Path.DirectorySeparatorChar + testName +
                                  Path.DirectorySeparatorChar + "complexDiv_files" + Path.DirectorySeparatorChar +
                                  "main.css")));
            cssFiles.Add(
                XMLWorkerHelper.GetCSS(
                    File.OpenRead(RESOURCES + Path.DirectorySeparatorChar + testPath + Path.DirectorySeparatorChar + testName +
                                  Path.DirectorySeparatorChar + "complexDiv_files" + Path.DirectorySeparatorChar +
                                  "widget082.css")));
            StyleAttrCSSResolver cssResolver = new StyleAttrCSSResolver(cssFiles);
            HtmlPipelineContext hpc =
                new HtmlPipelineContext(
                    new CssAppliersImpl(new XMLWorkerFontProvider(RESOURCES + @"\tool\xml\examples\fonts")));
            hpc.SetAcceptUnknown(true).AutoBookmark(true).SetTagFactory(Tags.GetHtmlTagProcessorFactory());
            hpc.SetImageProvider(new SampleTestImageProvider());
            hpc.SetPageSize(doc.PageSize);
            HtmlPipeline htmlPipeline = new HtmlPipeline(hpc, new PdfWriterPipeline(doc, pdfWriter));
            IPipeline pipeline = new CssResolverPipeline(cssResolver, htmlPipeline);
            XMLWorker worker = new XMLWorker(pipeline, true);
            XMLParser p = new XMLParser(true, worker, Encoding.GetEncoding("UTF-8"));
            p.Parse(File.OpenRead(inputHtml), Encoding.GetEncoding("UTF-8"));
            doc.Close();
        }
Пример #31
0
        public void VerticalPositionTest0() {
            String file = "vertical_position.pdf";

            Document document = new Document();
            PdfWriter writer = PdfWriter.GetInstance(document, File.Create(OUTPUT_FOLDER + file));
            document.Open();

            writer.PageEvent = new CustomPageEvent();

            PdfPTable table = new PdfPTable(2);
            for (int i = 0; i < 100; i++) {
                table.AddCell("Hello " + i);
                table.AddCell("World " + i);
            }

            document.Add(table);

            document.NewPage();

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 1000; i++) {
                sb.Append("some more text ");
            }
            document.Add(new Paragraph(sb.ToString()));

            document.Close();

            // compare
            CompareTool compareTool = new CompareTool();
            String errorMessage = compareTool.CompareByContent(OUTPUT_FOLDER + file, TEST_RESOURCES_PATH + file,
                OUTPUT_FOLDER, "diff");
            if (errorMessage != null) {
                Assert.Fail(errorMessage);
            }
        }
        public void ASPXToPDF(HtmlTable objhtml1,  HtmlTable objhtml2)
        {
            string fileName = "AsignacionFolios.pdf";
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.Clear();

            StringWriter sw1 = new StringWriter();
            HtmlTextWriter hw1 = new HtmlTextWriter(sw1);
            objhtml1.RenderControl(hw1);

            StringWriter sw2 = new StringWriter();
            HtmlTextWriter hw2 = new HtmlTextWriter(sw2);
            objhtml2.RenderControl(hw2);

            StringReader sr1 = new StringReader(sw1.ToString());
            StringReader sr2 = new StringReader(sw2.ToString());

            Document pdfDoc = new Document(PageSize.A2, 5f, 5f, 5f, 5f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr1);
            pdfDoc.NewPage();

            htmlparser.Parse(sr2);
            pdfDoc.Close();

            HttpContext.Current.Response.ContentType = "application/pdf";
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
            HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            HttpContext.Current.Response.Write(pdfDoc);
            HttpContext.Current.Response.End();
        }
        public void Go()
        {
            var outputFile = Helpers.IO.GetClassOutputPath(this);
            var parsedHtml = RemoveImage(HTML);
            Console.WriteLine(parsedHtml);

            using (var xmlSnippet = new StringReader(parsedHtml))
            {
                using (FileStream stream = new FileStream(
                    outputFile,
                    FileMode.Create,
                    FileAccess.Write))
                {
                    using (var document = new Document())
                    {
                        PdfWriter writer = PdfWriter.GetInstance(
                          document, stream
                        );
                        document.Open();
                        XMLWorkerHelper.GetInstance().ParseXHtml(
                          writer, document, xmlSnippet
                        );
                    }
                }
            }
        }
Пример #34
0
        public int Convert(string from, string to)
        {
            _logger.DebugFormat("Text转换为Pdf, {0},到:{1}", from, to);

            try
            {
                var content = File.ReadAllText(@from, Encoding.Default);

                Document document = new Document();
                BaseFont bf = BaseFont.CreateFont("c:\\windows\\fonts\\SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

                Font font = new Font(bf);

                PdfWriter.GetInstance(document, new FileStream(@to, FileMode.Create));
                document.Open();

                document.Add(new Paragraph(content, font));
                document.Close();

                return ErrorMessages.Success;
            }
            catch(Exception ex)
            {
                throw new ConverterException(ErrorMessages.TextToPdfFailed, ex);
            }
        }
Пример #35
0
        public bool TryCreatePdf(string nameBank)
        {
            try
            {
                using (FileStream file = new FileStream(String.Format(path,nameBank), FileMode.Create))
                {
                    Document document = new Document(PageSize.A7);
                    PdfWriter writer = PdfWriter.GetInstance(document, file);

                    /// Create metadate pdf file
                    document.AddAuthor("");
                    document.AddLanguage("pl");
                    document.AddSubject("Payment transaction");
                    document.AddTitle("Transaction");
                    /// Create text in pdf file
                    document.Open();
                    document.Add(new Paragraph(_przelew+"\n"));
                    document.Add(new Paragraph(String.Format("Bank {0}: zaprasza\n",nameBank)));
                    document.Add(new Paragraph(DateTime.Now.ToString()));
                    document.Close();
                    writer.Close();
                    file.Close();
                    return true;
                }
            }
            catch (SystemException ex)
            {
                return false;
            }
        }
Пример #36
0
// ---------------------------------------------------------------------------        
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) { 
        byte[] pdf = new Superimposing().CreatePdf();
        // Create a reader
        PdfReader reader = new PdfReader(pdf);
        using (MemoryStream ms = new MemoryStream()) {     
          // step 1
          using (Document document = new Document(PageSize.POSTCARD)) {
            // step 2
            PdfWriter writer = PdfWriter.GetInstance(document, ms);
            // step 3
            document.Open();
            // step 4
            PdfContentByte canvas = writer.DirectContent;
            PdfImportedPage page;
            for (int i = 1; i <= reader.NumberOfPages; i++) {
              page = writer.GetImportedPage(reader, i);
              canvas.AddTemplate(page, 1f, 0, 0, 1, 0, 0);
            }
          } 
          zip.AddEntry(RESULT, ms.ToArray());
        }
        zip.AddEntry(SOURCE, pdf);
        zip.Save(stream);            
      }        
    }
Пример #37
0
 virtual public void CreateAllSamples() {
     bool success = true;
     foreach (String str in list) {
         try {
             Console.WriteLine(str);
             Document doc = new Document();
             PdfWriter writer = null;
             try {
                 writer = PdfWriter.GetInstance(doc,
                     new FileStream(TARGET + "/" + str + "Test.pdf", FileMode.Create));
             }
             catch (DocumentException e) {
                 Console.WriteLine(e);
             }
             doc.Open();
             StreamReader bis = File.OpenText(RESOURCE_TEST_PATH + "/snippets/" + str + "snippet.html");
             XMLWorkerHelper helper = XMLWorkerHelper.GetInstance();
             helper.ParseXHtml(writer, doc, bis);
             doc.Close();
         }
         catch (Exception e) {
             Console.Write(e);
             success = false;
         }
     }
     if (!success) {
         Assert.Fail();
     }
 }
Пример #38
0
        public static bool generate(User user, string path)
        {
            document = new Document(PageSize.A4, 50, 50, 25, 25);

            var output = new MemoryStream();
            var writer = PdfWriter.GetInstance(document, new FileStream(path + "/BS-" + DateTime.Now.Month + "-" + DateTime.Now.Year + "-" + user.Firstname + "-" + user.Lastname + ".pdf", FileMode.Create));

            document.Open();

            // création du logo
            Image logo = iTextSharp.text.Image.GetInstance("logo.png");
            logo.ScaleAbsoluteWidth(200);
            logo.ScaleAbsoluteHeight(50);
            PdfPCell cellLogo = new PdfPCell(logo);
            cellLogo.Border = Rectangle.NO_BORDER;
            cellLogo.PaddingBottom = 8;

            // création du titre
            var title = new Paragraph("BULLETIN DE SALAIRE", titleFont);
            title.Alignment = Element.ALIGN_RIGHT;
            PdfPCell cellTitle = new PdfPCell(title);
            cellTitle.Border = Rectangle.NO_BORDER;
            cellTitle.HorizontalAlignment = 2; //0=Left, 1=Centre, 2=Right

            // création du tableau
            PdfPTable tableTitle = new PdfPTable(2);
            tableTitle.DefaultCell.Border = Rectangle.NO_BORDER;
            tableTitle.WidthPercentage = 100;

            PdfPCell cellAdresseSuperp = new PdfPCell(new Paragraph("89, quais des Chartrons \n33000 BORDEAUX", subTitleFont));
            cellAdresseSuperp.HorizontalAlignment = 0;
            cellAdresseSuperp.Border = Rectangle.NO_BORDER;

            PdfPCell cellDUMec = new PdfPCell(new Paragraph(user.Lastname + " " + user.Firstname + "\n" + user.Address, subTitleFont));
            cellDUMec.HorizontalAlignment = 2;
            cellDUMec.Border = Rectangle.NO_BORDER;

            // ajout de la cell du logo
            tableTitle.AddCell(cellLogo);

            // ajout de la cell du titre
            tableTitle.AddCell(cellTitle);

            tableTitle.AddCell(cellAdresseSuperp);
            tableTitle.AddCell(cellDUMec);

            // Ajout du titre principal
            tableTitle.AddCell(getTitle());

            //******************************************************************************/
            //***********************   ABSENCES   *****************************************/
            //******************************************************************************/

            generateAbsences(tableTitle, user);

            generateTableSalary(user);

            document.Close();
            return true;
        }
Пример #39
0
        protected void initFile(bool bBlackAndWhite = false)
        {
            m_doc = new Document();
            string folder = Settings.Default["pdffolder"].ToString() + m_strFolder;
            System.IO.Directory.CreateDirectory(folder );
            string fileName = folder + "/"+m_strTitle;
            if (bBlackAndWhite)
                fileName += "BW.pdf";
            else
                fileName += ".pdf";

            m_writer = PdfWriter.GetInstance(m_doc, new System.IO.FileStream(fileName, System.IO.FileMode.Create));
            m_doc.Open();
            m_fSmall = new iTextSharp.text.Font();
            m_fSmall.Size = 10;

            m_fBig = new iTextSharp.text.Font();
            m_fBig.Size = 40;
            m_fBig.Color = bBlackAndWhite ? BaseColor.BLACK : getNextColor();
            //            m_fBig.SetStyle("bold");

            m_fNorm = new iTextSharp.text.Font();
            m_fNorm.Size = 20;
            m_fNorm.Color = new BaseColor(m_colorText);

            m_doc.Add(new Paragraph("Name:____________________________________________  Date:______________"/*, fSmall*/));
            m_doc.Add(new Paragraph(m_strTitle, m_fBig));
            m_doc.Add(new Paragraph("   "));
        }
Пример #40
0
        public void TextLeadingTest() {
            String file = "phrases.pdf";

            Document document = new Document();
            PdfWriter writer = PdfWriter.GetInstance(document, File.Create(OUTPUT_FOLDER + file));
            document.Open();

            Phrase p1 = new Phrase("first, leading of 150");
            p1.Leading = 150;
            document.Add(p1);
            document.Add(Chunk.NEWLINE);

            Phrase p2 = new Phrase("second, leading of 500");
            p2.Leading = 500;
            document.Add(p2);
            document.Add(Chunk.NEWLINE);

            Phrase p3 = new Phrase();
            p3.Add(new Chunk("third, leading of 20"));
            p3.Leading = 20;
            document.Add(p3);

            document.Close();

            // compare
            CompareTool compareTool = new CompareTool();
            String errorMessage = compareTool.CompareByContent(OUTPUT_FOLDER + file, TEST_RESOURCES_PATH + file, OUTPUT_FOLDER, "diff");
            if (errorMessage != null) {
                Assert.Fail(errorMessage);
            }
        }
Пример #41
0
 private void button3_Click(object sender, EventArgs e)
 {
     using (SaveFileDialog sfd = new SaveFileDialog()
     {
         Filter = "PDF File|*.pdf", ValidateNames = true
     })
     {
         if (sfd.ShowDialog() == DialogResult.OK)
         {
             iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.A4.Rotate());
             try
             {
                 PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.Create));
                 doc.Open();
                 doc.Add(new iTextSharp.text.Paragraph(detailsBox.Text));
             }
             catch (Exception ex)
             {
                 MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
             finally
             {
                 doc.Close();
             }
         }
     }
 }
Пример #42
0
        /// <summary>
        /// Creates a MemoryStream but does not dispose it.
        /// </summary>
        /// <param name="members"></param>
        /// <param name="expiration"></param>
        /// <returns></returns>
        public static MemoryStream CreateCards(IEnumerable<Member> members, DateTime expiration)
        {
            iTextSharp.text.Document doc = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(CARD_WIDTH, CARD_HEIGHT));
            MemoryStream memStream = new MemoryStream();
            PdfWriter writer = PdfWriter.GetInstance(doc, memStream);
            writer.CloseStream = false;
            doc.Open();

            foreach (var member in members)
            {
                foreach (var passport in new[] { false, true})
                {
                    Render_FrontBase(writer.DirectContentUnder, expiration);
                    Render_FrontContent(writer.DirectContent, member);
                    doc.NewPage();
                    Render_BackBase(writer.DirectContentUnder);
                    Render_BackContent(writer.DirectContent, member, passport);
                    doc.NewPage();
                }
            }

            doc.Close();
            byte[] buf = new byte[memStream.Position];
            memStream.Position = 0;

            return memStream;
        }
Пример #43
0
// ---------------------------------------------------------------------------
    public void SendPdf(Stream stream, string text) {
      // setting some response headers
      HttpResponse Response = HttpContext.Current.Response;
      Response.ContentType = "application/pdf";
      Response.AppendHeader("Expires", "0");
      Response.AppendHeader(
        "Cache-Control",
        "must-revalidate, post-check=0, pre-check=0"
      );
      Response.AppendHeader("Pragma", "public");
          
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        document.Add(new Paragraph(String.Format(
          "HTTP request using the {0} method: ",
          WebContext.Request.HttpMethod
        )));                   
        document.Add(new Paragraph(text));
      }
    }
        // to generate the report call the GeneratePDFReport static method.
        // The pdf file will be generated in the SupermarketChain.ConsoleClient folder
        // TODO measures are missing
        // TODO code refactoring to limitr repeated chunks
        public static void GeneratePDFReport()
        {
            Document doc = new Document(iTextSharp.text.PageSize.A4, 10, 10, 40, 35);
            string filePath = @"..\..\..\..\Reports\salesReports.pdf";
            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Create));
            doc.Open();
            PdfPTable table = new PdfPTable(5);

            Font verdana = FontFactory.GetFont("Verdana", 16, Font.BOLD);
            Font verdana2 = FontFactory.GetFont("Verdana", 12, Font.BOLD);

            PdfPCell header = new PdfPCell(new Phrase("Aggregated Sales Report", verdana));
            header.Colspan = 5;
            header.HorizontalAlignment = 1;
            table.AddCell(header);

            double totalSales = PourReportData(table);

            PdfPCell totalSum = new PdfPCell(new Phrase("Grand total:"));
            totalSum.Colspan = 4;
            totalSum.HorizontalAlignment = 2;
            totalSum.BackgroundColor = new BaseColor(161, 212, 224);
            table.AddCell(totalSum);

            PdfPCell totalSumNumber = new PdfPCell(new Phrase(String.Format("{0:0.00}", totalSales), verdana));
            totalSumNumber.BackgroundColor = new BaseColor(161, 212, 224);
            table.AddCell(totalSumNumber);

            doc.Add(table);
            doc.Close();

            DirectoryInfo directoryInfo = new DirectoryInfo(filePath);
            Console.WriteLine("Pdf report generated.");
            Console.WriteLine("File:  {0}", directoryInfo.FullName);
        }
Пример #45
0
        /// <summary>
        /// Save a pdf file in  "../../test.pdf".
        /// </summary>
        /// <param name="deals">Expect Collection of objects that have Name, Address, ProductName and formula.</param>
        public void GenerateReport(IEnumerable<PdfReportModel> deals)
        {
            FileStream fileStream = new FileStream(ReportsPath, FileMode.Create, FileAccess.Write, FileShare.None);
            Rectangle pageSize = new Rectangle(PageSize.A4);
            Document reportDocument = new Document(pageSize);
            PdfWriter pdfWriter = PdfWriter.GetInstance(reportDocument, fileStream);
            var boldFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 17);

            reportDocument.Open();

            PdfPTable reportTable = new PdfPTable(6);
            reportTable.HorizontalAlignment = Element.ALIGN_LEFT;
            PdfPCell headerCell = new PdfPCell(new Phrase("Produced products information", boldFont));
            headerCell.Colspan = 6;
            headerCell.HorizontalAlignment = 0;
            reportTable.AddCell(headerCell);

            this.PutHeadCells(reportTable);

            foreach (var deal in deals)
            {
                reportTable.AddCell(deal.ProductName);
                reportTable.AddCell(deal.Quantity);
                reportTable.AddCell(deal.PricePerUnit);
                reportTable.AddCell(deal.Formula);
                reportTable.AddCell(deal.Address);
                reportTable.AddCell(deal.Total);
            }

            reportDocument.Add(reportTable);
            reportDocument.Close();
        }
Пример #46
0
 public static void Export(DetailsView dvGetStudent)
 {
     int rows = dvGetStudent.Rows.Count;
     int columns = dvGetStudent.Rows[0].Cells.Count;
     int pdfTableRows = rows;
     iTextSharp.text.Table PdfTable = new iTextSharp.text.Table(2, pdfTableRows);
     PdfTable.BorderWidth = 1;
     PdfTable.Cellpadding = 0;
     PdfTable.Cellspacing = 0;
     for (int rowCounter = 0; rowCounter < rows; rowCounter++)
     {
         for (int columnCounter = 0; columnCounter < columns; columnCounter++)
         {
             string strValue = dvGetStudent.Rows[rowCounter].Cells[columnCounter].Text;
             PdfTable.AddCell(strValue);
         }
     }
     Document Doc = new Document();
     PdfWriter.GetInstance(Doc, HttpContext.Current.Response.OutputStream);
     Doc.Open();
     Doc.Add(PdfTable);
     Doc.Close();
     HttpContext.Current.Response.ContentType = "application/pdf";
     HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=StudentDetails.pdf");
     HttpContext.Current.Response.End();
 }
        protected void generatePDFButton_Click(object sender, EventArgs e)
        {
            PdfPTable pdfPTable = new PdfPTable(CreatedStudentInformationGridView.HeaderRow.Cells.Count);

            foreach (TableCell headerCell in CreatedStudentInformationGridView.HeaderRow.Cells)
            {
                PdfPCell pfdPCell = new PdfPCell(new Phrase(headerCell.Text));
                //pfdPCell.BackgroundColor = new BaseColor(newCenterGridView.HeaderStyle.ForeColor);
                pdfPTable.AddCell(pfdPCell);
            }

            foreach (GridViewRow gridViewRow in CreatedStudentInformationGridView.Rows)
            {
                foreach (TableCell tableCell in gridViewRow.Cells)
                {

                    PdfPCell pfdPCell = new PdfPCell(new Phrase(tableCell.Text));
                    //pfdPCell.BackgroundColor = new BaseColor(newCenterGridView.HeaderStyle.ForeColor);
                    pdfPTable.AddCell(pfdPCell);
                }
            }
            Document pdfDocument = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
            PdfWriter.GetInstance(pdfDocument, Response.OutputStream);

            pdfDocument.Open();
            pdfDocument.Add(pdfPTable);
            pdfDocument.Close();

            Response.ContentType = "application/pdf";
            Response.AppendHeader("content-disposition", "attachment;filename=NewCenter.pdf");
            Response.Write(pdfDocument);
            Response.Flush();
            Response.End();
        }
        private void btn_Update_Click(object sender, EventArgs e)
        {
            //the library for create a new pdf document
            iTextSharp.text.Document report = new iTextSharp.text.Document();
            //file path of newly created pdf file to save
            PdfWriter.GetInstance(report, new FileStream(@"C:\Users\Asus\Desktop\UPLOADFILES\" + textboxFileName.Text, FileMode.Create));
            //Author name, need for create a new pdf document
            report.AddAuthor(lbl_Author.Text);
            //Creation Date, need for create a new pdf document
            report.AddCreationDate();
            //Creator, need for create a new pdf document
            report.AddCreator(lbl_Creator.Text);
            //Subject, need for create a new pdf document
            report.AddSubject(lbl_Subject.Text);
            //Keywords, need for create a new pdf document
            report.AddKeywords(lbl_Keyword.Text);

            if (report.IsOpen() == false)
            {
                //open report for create a new pdf document
                report.Open();
            }
            //Paragraph, need for create a new pdf document
            report.Add(new Paragraph(rtxt_Paragraph.Text));

            //open the connection
            db.openConnection();
            //a command line for update the document
            SqlCommand query = new SqlCommand("UPDATE Table_DOCUMENT SET file_Path = @fp, u_ID = @uid WHERE file_ID = @fid", db.getConnection());

            //add the value in the label to @fp
            query.Parameters.AddWithValue("@fp", labelFilePath.Text);
            //add the value in the combobox to @uid
            query.Parameters.AddWithValue("@uid", comboboxUserID.Text);
            //add the value in the label to @fid
            query.Parameters.AddWithValue("@fid", labelFileID.Text);

            //ecevute the query
            if (query.ExecuteNonQuery() == 1)
            {
                MessageBox.Show("DATA WERE UPDATED", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
                //return the default values
                labelFilePath.Text     = @"C:\Users\Asus\Desktop\UPLOADFILES";
                textboxFilePath.Text   = "";
                labelFileID.Text       = "";
                lbl_FileName.Text      = "";
                labelCreationDate.Text = "";
                comboboxUserID.Text    = " ";
                rtxt_Paragraph.Text    = "";
            }
            else
            {
                MessageBox.Show("ERROR", "Message Box", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
            }
            //close the report
            report.Close();
            //close the connection
            db.closeConnection();
        }
Пример #49
0
        // open the reader
        public void EditPDF()
        {
            PdfReader reader = new PdfReader(oldFile);

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

            // open the writer
            FileStream fs     = new FileStream(newFile, FileMode.Create, FileAccess.Write);
            PdfWriter  writer = PdfWriter.GetInstance(document, fs);

            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.BLACK);
            cb.SetFontAndSize(bf, 12);

            #region edit pdf in half 1
            // write the text in the pdf content
            cb.BeginText();
            string text = "507586";
            // put the alignment and coordinates here
            cb.ShowTextAligned(1, text, 430, 510, 0);
            cb.EndText();
            cb.BeginText();
            text = "S1 - 4";
            // put the alignment and coordinates here
            cb.ShowTextAligned(2, text, 500, 574, 0);
            cb.EndText();
            #endregion

            #region edit pdf in half 2
            // write the text in the pdf content
            cb.BeginText();
            text = "chungDepZai";
            // put the alignment and coordinates here
            cb.ShowTextAligned(1, text, 430, 225, 0);
            cb.EndText();
            cb.BeginText();
            text = "AAAAAAA";
            // put the alignment and coordinates here
            cb.ShowTextAligned(2, text, 500, 287, 0);
            cb.EndText();
            #endregion
            // create the new page and add it to the pdf
            PdfImportedPage page = writer.GetImportedPage(reader, 1);
            cb.AddTemplate(page, 0, 0);

            // close the streams and voilá the file should be changed :)
            document.Close();
            fs.Close();
            writer.Close();
            reader.Close();
        }
Пример #50
0
        private void button1_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog sfd = new SaveFileDialog()
            {
                Filter = "PDF File|*.pdf", ValidateNames = true
            })
            {
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.A4, 10f, 10f, 140f, 10f);
                    try
                    {
                        PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.Create));

                        doc.Open();
                        iTextSharp.text.Image JPG = iTextSharp.text.Image.GetInstance("12046919_1726331607595049_7849083510719349652_n.jpg");
                        JPG.SetAbsolutePosition((PageSize.LETTER.Width - JPG.ScaledWidth) / 2, (PageSize.LETTER.Height - JPG.ScaledHeight) / 2);

                        JPG.ScalePercent(30f);
                        //JPG.SetAbsolutePosition(0, doc.PageSize.Height - JPG.ScaledHeight);
                        doc.Add(JPG);


                        richTextBox1.SelectAll();
                        richTextBox1.SelectionHangingIndent = 20;
                        doc.Add(new iTextSharp.text.Paragraph(richTextBox1.Text.PadLeft(20)));
                        PdfPTable table = new PdfPTable(dataGridView1.Columns.Count);

                        for (int j = 0; j < dataGridView1.Columns.Count; j++)
                        {
                            table.AddCell(new Phrase(dataGridView1.Columns[j].HeaderText));
                        }

                        table.HeaderRows = 1;

                        for (int i = 0; i < dataGridView1.Rows.Count; i++)
                        {
                            for (int k = 0; k < dataGridView1.Columns.Count; k++)
                            {
                                if (dataGridView1[k, i].Value != null)
                                {
                                    table.AddCell(new Phrase(dataGridView1[k, i].Value.ToString()));
                                }
                            }
                        }
                        doc.Add(table);
                        doc.Add(new iTextSharp.text.Paragraph(textBox1.Text.PadLeft(20)));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    finally
                    {
                        doc.Close();
                    }
                }
            }
        }
Пример #51
0
        public void ExportDataTableToPdf(DataTable dtblTable, String strPdfPath, string strHeader)
        {
            System.IO.FileStream     fs       = new FileStream(strPdfPath, FileMode.Create, FileAccess.Write, FileShare.None);
            iTextSharp.text.Document document = new iTextSharp.text.Document();
            document.SetPageSize(iTextSharp.text.PageSize.A4);
            PdfWriter writer = PdfWriter.GetInstance(document, fs);

            document.Open();

            //Report Header
            BaseFont  bfntHead   = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            Paragraph prgHeading = new Paragraph();

            prgHeading.Alignment = Element.ALIGN_CENTER;
            prgHeading.Add(new Chunk(strHeader.ToUpper()));
            document.Add(prgHeading);

            //Author
            Paragraph prgAuthor = new Paragraph();
            BaseFont  btnAuthor = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            prgAuthor.Alignment = Element.ALIGN_RIGHT;
            prgAuthor.Add(new Chunk("Author : Dotnet Mob"));
            prgAuthor.Add(new Chunk("\nRun Date : " + DateTime.Now.ToShortDateString()));
            document.Add(prgAuthor);

            //Add a line seperation
            Paragraph p = new Paragraph();

            document.Add(p);

            //Add line break
            document.Add(new Chunk("\n"));

            //Write the table
            PdfPTable table = new PdfPTable(dtblTable.Columns.Count);
            //Table header
            BaseFont btnColumnHeader = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            for (int i = 0; i < dtblTable.Columns.Count; i++)
            {
                PdfPCell cell = new PdfPCell();
                cell.AddElement(new Chunk(dtblTable.Columns[i].ColumnName.ToUpper()));
                table.AddCell(cell);
            }
            //table Data
            for (int i = 0; i < dtblTable.Rows.Count; i++)
            {
                for (int j = 0; j < dtblTable.Columns.Count; j++)
                {
                    table.AddCell(dtblTable.Rows[i][j].ToString());
                }
            }

            document.Add(table);
            document.Close();
            writer.Close();
            fs.Close();
        }
        public bool CreateReport()
        {
            LoadPotentialCategories();
            _TotalIncome = new ReportObject.Snapshot();
            bool isSuccessful = false;

            iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.LEGAL);

            try
            {
                //set up RunReport event overrides & create doc
                string reportFileName = Path.GetFullPath(reportObject.ReportTempFileFullName);
                if (!Directory.Exists(Path.GetDirectoryName(reportFileName)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(reportFileName));
                }
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(reportFileName, FileMode.Create));
                writer.PageEvent = this;

                PdfPTable table = new PdfPTable(_Columns);
                Image     gif   = Image.GetInstance(Resources.logo, BaseColor.WHITE);
                gif.ScalePercent(35);

                _reportFont = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL);

                document.AddTitle(reportObject.ReportTitle);

                document.SetPageSize(PageSize.LETTER);
                document.SetMargins(-50, -55, 10, 45);

                table.HeaderRows = 2;
                PrintReportHeader(table, gif);
                PrintReportDetailHeader(table);
                table.SetWidths(new float[] { 1.5f, 2, 1, 1, 1.5f });
                foreach (PotentialCategoryInfo categoryInfo in _PotentialCategories)
                {
                    PrintReportDetail(table, categoryInfo);
                }
                PrintReportDetailDisclaimer(table);

                document.Open();
                document.Add(table);
                document.Close();

                isSuccessful = true;
            }
            catch (DocumentException de)
            {
                reportObject.ReportError      = de.Message;
                reportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            catch (IOException ioe)
            {
                reportObject.ReportError      = ioe.Message;
                reportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }

            return(isSuccessful);
        }
Пример #53
0
        private void BloodToolStripMenuItem_Click(object sender, EventArgs e)
        {
            saveFileDialog1.Title      = "Сохранение документа";
            saveFileDialog1.FileName   = "Группы крови";
            saveFileDialog1.DefaultExt = "*.pdf";
            saveFileDialog1.Filter     = "Файлы PDF (*.pdf)|*.pdf|Все файлы (*.*)|*.*";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string SaveFileName = saveFileDialog1.FileName;

                //Объект документа пдф
                iTextSharp.text.Document doc = new iTextSharp.text.Document();
                //Создаем объект записи пдф-документа в файл
                PdfWriter.GetInstance(doc, new FileStream(SaveFileName, FileMode.Create));

                //Открываем документ
                doc.Open();

                //Определение шрифта необходимо для сохранения кириллического текста
                //Иначе мы не увидим кириллический текст
                //Если мы работаем только с англоязычными текстами, то шрифт можно не указывать
                string               FONT_LOCATION = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "arial.TTF"); //определяем В СИСТЕМЕ(чтобы не копировать файл) расположение шрифта arial.ttf
                BaseFont             baseFont      = BaseFont.CreateFont(FONT_LOCATION, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);        //создаем шрифт
                iTextSharp.text.Font fontParagraph = new iTextSharp.text.Font(baseFont, 17, iTextSharp.text.Font.NORMAL);                   //регистрируем + можно задать параметры для него(17 - размер, последний параметр - стиль)
                                                                                                                                            //Создаем объект таблицы и передаем в нее число столбцов таблицы из нашего датасета
                PdfPTable table = new PdfPTable(2);                                                                                         //MyDataSet.Tables[i].Columns.Count);
                                                                                                                                            //Добавим в таблицу общий заголовок
                PdfPCell cell = new PdfPCell(new Phrase("Группы крови коров"))
                {
                    Colspan             = 2,
                    HorizontalAlignment = 1,
                    //Убираем границу первой ячейки, чтобы был как заголовок
                    Border = 0
                };
                table.AddCell(cell);
                //Сначала добавляем заголовки таблицы
                cell = new PdfPCell(new Phrase(new Phrase("Номер коровы", fontParagraph)));
                //Фоновый цвет (необязательно, просто сделаем по красивее)
                cell.BackgroundColor = BaseColor.LIGHT_GRAY;
                table.AddCell(cell);
                cell = new PdfPCell(new Phrase(new Phrase("Группа крови", fontParagraph)));
                cell.BackgroundColor = BaseColor.LIGHT_GRAY;
                table.AddCell(cell);
                //Добавляем все остальные ячейки
                for (int j = 0; j < analysis_of_bloodDataGridView.RowCount - 1; j++)
                {
                    //for (int k = 0; k < 3; k++)
                    //{
                    table.AddCell(new Phrase(analysis_of_bloodDataGridView.Rows[j].Cells[1].Value.ToString(), fontParagraph));
                    table.AddCell(new Phrase(analysis_of_bloodDataGridView.Rows[j].Cells[3].Value.ToString(), fontParagraph));
                    //}
                }
                //Добавляем таблицу в документ
                doc.Add(table);
                //Закрываем документ
                doc.Close();
                Process.Start(saveFileDialog1.FileName);
            }
        }
        public bool CreateReport()
        {
            bool isSuccessful = false;

            iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.LEGAL.Rotate());
            try
            {
                //set up RunReport event overrides & create doc
                //_pageCount = 1;
                ATFOpenRecordsReport events = this;
                PdfWriter            writer = PdfWriter.GetInstance(document, new FileStream(ReportObject.ReportTempFileFullName, FileMode.Create));
                writer.PageEvent = events;

                MultiColumnText columns = new MultiColumnText(document.PageSize.Top - 148, document.PageSize.Height - (170));
                columns.AddSimpleColumn(-51, document.PageSize.Width + 60);

                //set up tables, etc...
                var table = new PdfPTable(21);
                table.WidthPercentage = 85;// document.PageSize.Width;
                var cell = new PdfPCell();
                var gif  = Image.GetInstance(Common.Properties.Resources.logo, BaseColor.WHITE);
                gif.ScalePercent(25);
                runReport = new RunReport();
                document.Open();
                document.SetPageSize(PageSize.LEGAL.Rotate());
                document.SetMargins(-100, -100, 10, 35);
                document.AddTitle(string.Format("{0}: {1}", ReportObject.ReportTitle, DateTime.Now.ToString("MM/dd/yyyy")));

                //here add detail
                WriteDetail(table, 21);
                columns.AddElement(table);
                document.Add(columns);

                string          gunText          = "Total Number of Guns: " + TotalNumberOfGuns;
                MultiColumnText columnBottomPage = new MultiColumnText(document.PageSize.Bottom, 25);
                columnBottomPage.AddSimpleColumn(-51, document.PageSize.Width + 60);
                PdfPTable tableBottom = new PdfPTable(1);
                tableBottom.WidthPercentage = 85;// document.PageSize.Width;
                WriteCell(tableBottom, gunText, ReportFontLargeBold, 1, Element.ALIGN_LEFT, Rectangle.NO_BORDER);
                columnBottomPage.AddElement(tableBottom);
                document.Add(columnBottomPage);

                document.Close();
                //OpenFile(ReportObject.ReportTempFileFullName);
                //CreateReport();
                isSuccessful = true;
            }
            catch (DocumentException de)
            {
                ReportObject.ReportError      = de.Message;
                ReportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            catch (IOException ioe)
            {
                ReportObject.ReportError      = ioe.Message;
                ReportObject.ReportErrorLevel = (int)LogLevel.ERROR;
            }
            return(isSuccessful);
        }
Пример #55
0
        public void FormToPdf(DataTable srcDgv)
        {
            //iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(144, 720);
            iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(1366, 720);
            pageSize.BackgroundColor = new Color(0xFF, 0xFF, 0xDE);

            Document document = new Document(pageSize);

            string newFile = Server.MapPath("~/wordInfo/") + DateTime.Now.ToString("yyyyMMddHHmmssss") + ".pdf";

            //string newFile = "c://" + DateTime.Now.ToString("yyyyMMddHHmmssss") + ".pdf";
            PdfWriter.GetInstance(document, new FileStream(newFile, FileMode.Create));
            document.Open();
            BaseFont bfChinese = BaseFont.CreateFont("C://WINDOWS//Fonts//simsun.ttc,1", BaseFont.IDENTITY_H,
                                                     BaseFont.NOT_EMBEDDED);

            iTextSharp.text.Font fontChinese = new iTextSharp.text.Font(bfChinese, 12,
                                                                        iTextSharp.text.Font.NORMAL, new iTextSharp.text.Color(0, 0, 0));

            StringBuilder sbBuilder = new StringBuilder();

            sbBuilder.Append("姓名   ");
            sbBuilder.Append("性别   ");
            sbBuilder.Append("年龄   ");
            sbBuilder.Append("学历   ");
            sbBuilder.Append("手机   ");
            sbBuilder.Append("电子邮件   ");
            sbBuilder.Append("英语等级   ");
            sbBuilder.Append("求职意向   ");
            sbBuilder.Append("工作地点   ");
            sbBuilder.Append("工作年限   ");
            sbBuilder.Append("期望薪水   ");
            sbBuilder.Append("毕业院校   ");
            sbBuilder.Append("专业   ");
            sbBuilder.Append("最近单位   ");
            sbBuilder.Append("最近职位   ");
            sbBuilder.Append("接收时间   ");
            sbBuilder.Append("\n");

            //输出控件中的记录
            for (int i = 0; i < srcDgv.Rows.Count; i++)
            {
                for (int j = 0; j < srcDgv.Columns.Count; j++)
                {
                    sbBuilder.Append(srcDgv.Rows[i][j].ToString().Trim() + "   ");
                }
                sbBuilder.Append("\n");
            }
            //导出文本的内容:
            document.Add(new Paragraph(sbBuilder.ToString(), fontChinese));
            //导出图片:
            //iTextSharp.text.Image jpeg = iTextSharp.text.Image.GetInstance(Path.GetFullPath("1.jpg"));
            //document.Add(jpeg);

            //注意一定要关闭,否则PDF中的内容将得不到保存

            document.Close();
            Page.RegisterStartupScript("alt", "<script>alert('数据成功导出!')</script>");
        }
Пример #56
0
 private iTextSharp.text.Document CreatePagePDF(string strFilePath, iTextSharp.text.Rectangle rectPaperSize, float marginLeft, float marginRight, float marginTop, float marginBottom)
 {
     iTextSharp.text.Document      objPDFDoc = new iTextSharp.text.Document(rectPaperSize, marginLeft, marginRight, marginTop, marginBottom);
     iTextSharp.text.pdf.PdfWriter writer    = iTextSharp.text.pdf.PdfWriter.GetInstance(objPDFDoc,
                                                                                         new FileStream(strFilePath, FileMode.Create));
     objPDFDoc.Open();
     return(objPDFDoc);
 }
        public bool CreateReport(System.Data.DataSet theData)
        {
            bool isSuccessful = false;

            iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.LETTER.Rotate());

            try
            {
                //set up RunReport event overrides & create doc
                LoanListingReport events = this;

                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(reportTempFileFullName, FileMode.Create));
                writer.PageEvent = events;

                //set up tables, etc...
                PdfPTable table = new PdfPTable(18);
                PdfPCell  cell  = new PdfPCell();
                Image     gif   = Image.GetInstance(Resources.logo, BaseColor.WHITE);

                _reportFont          = FontFactory.GetFont("Arial", 8, iTextSharp.text.Font.NORMAL);
                _reportFontLargeBold = FontFactory.GetFont("Arial", 10, iTextSharp.text.Font.BOLD);

                gif.ScalePercent(35);

                document.SetPageSize(PageSize.LETTER.Rotate());
                document.SetMargins(20, 20, 10, 45);
                document.AddTitle("Loan Inquiry Listing Report : " + DateTime.Now.ToString("MM/dd/yyyy"));

                ReportHeader(table, gif);
                ColumnHeaders(table);

                table.SetWidthPercentage(new float[] { 35F, 45F, 45F, 45F, 75F, 40F, 45F, 55F, 40F, 55F, 45F, 45F, 40F, 50F, 25F, 25F, 25F, 25F },
                                         PageSize.LETTER.Rotate());

                table.HeaderRows = 8;

                ReportDetail(table, theData);
                ReportLines(table, true, "", true, _reportFont);

                document.Open();
                document.Add(table);
                document.Close();

                isSuccessful = true;
            }
            catch (DocumentException de)
            {
                ReportError      = de.Message;
                ReportErrorLevel = (int)LogLevel.ERROR;
            }
            catch (IOException ioe)
            {
                ReportError      = ioe.Message;
                ReportErrorLevel = (int)LogLevel.ERROR;
            }

            return(isSuccessful);
        }
Пример #58
0
        private void button4_Click(object sender, EventArgs e)
        {
            /*-------------------------------------*/

            iTextSharp.text.Document raporum = new iTextSharp.text.Document();

            // PDF oluşturması ve konumun belirlenmesi
            Random r = new Random();

            PdfWriter.GetInstance(raporum, new FileStream("C:Raporum" + r.Next() + ".pdf", FileMode.Create));

            //PDF yi yazan özelliğine eklenecek

            raporum.AddAuthor("Selim Silgu"); // PDF Oluşturma Tarihi Ekle

            raporum.AddCreationDate();        // PDF Oluşturma Tarihi

            // PDF oluşturan kişi özelliğine yazılacak

            raporum.AddCreator("Selim Silgu");

            if (raporum.IsOpen() == false)
            {
                raporum.Open();
            }

            raporum.Add(new Paragraph("Ürün Fiyatı : " + urunFiyat.Text + " TL"));
            raporum.Add(new Paragraph("Seri Numarası : " + seriNumarasi.Text));
            raporum.Add(new Paragraph("Ürün ID : " + urunid.ToString()));
            raporum.Add(new Paragraph("Ürün Adı : " + urunAdText.Text));
            raporum.Add(new Paragraph("Ürün Modeli : " + UrunModel.Text));
            raporum.Add(new Paragraph("Islemci Hızı : " + islemciHız.Text));
            raporum.Add(new Paragraph("Cache Bellek : " + cache.Text));
            raporum.Add(new Paragraph("Islemci Teknolojisi : " + islemciTeknoloji.Text));
            raporum.Add(new Paragraph("Islemci Markası : " + islemciMarka.Text));
            raporum.Add(new Paragraph("Islemci Hızı : " + islemciHız.Text));
            raporum.Add(new Paragraph("Çekirdek Sayısı : " + cekirdekSayisi.Text));
            raporum.Add(new Paragraph("RAM Tipi :" + ramTip.Text));
            raporum.Add(new Paragraph("RAM Kapasitesi : " + ramKapasite.Text));
            raporum.Add(new Paragraph("RAM Markası : " + ramMarka.Text));
            raporum.Add(new Paragraph("Disk Türü : " + hddTur.Text));
            raporum.Add(new Paragraph("Disk Markası : " + hddMarka.Text));
            raporum.Add(new Paragraph("USB : " + usb.Text));
            raporum.Add(new Paragraph("Isletim Sistemi : " + isletimSistemi.Text));
            raporum.Add(new Paragraph("Ekran Kartı Tipi : " + ekranKartTip.Text));
            raporum.Add(new Paragraph("Ekran Kartı Markası : " + ekranMarka.Text));
            raporum.Add(new Paragraph("Ekran Kartı Chipset : " + chipset.Text));
            raporum.Add(new Paragraph("Ekran Kartı Kapasitesi : " + kapasite.Text));
            raporum.Add(new Paragraph("Çözünürlük : " + cozunurluk.Text));
            raporum.Add(new Paragraph("Kart Okuyucu : " + kartOkuyucu.Text));
            raporum.Add(new Paragraph("Kamera : " + kamera.Text));
            raporum.Add(new Paragraph("Garanti Süresi : " + GarantiSuresi.Text));
            MessageBox.Show("PDF Dosyanız Oluşmuştur.");

            raporum.Close();

            /*-------------------------------------*/
        }
Пример #59
0
        public ResultResponse GenerateWorkerBarcode(List <UserInformation> users)
        {
            ResultResponse resultResponse = new ResultResponse();

            var pgSize = new iTextSharp.text.Rectangle(100, 65);

            iTextSharp.text.Document doc = new iTextSharp.text.Document(pgSize, 0, 0, 0, 0);
            string   path     = HttpContext.Current.Server.MapPath("~/GenaratePDF/");
            DateTime dt       = DateTime.Now;
            string   fileName = dt.Minute.ToString() + dt.Second.ToString() + dt.Millisecond.ToString();

            PdfWriter.GetInstance(doc, new FileStream(path + fileName + ".pdf", FileMode.Create));
            //open the document for writing
            doc.Open();
            // doc.SetPageSize(new iTextSharp.text.Rectangle(100,65));
            PdfPTable pdftable = new PdfPTable(1);

            for (int i = 0; i < users.Count; i++)
            {
                int count = 0;
                iTextSharp.text.Font font = FontFactory.GetFont("Calibri", 6.0f, BaseColor.BLACK); // from 5.0f
                count++;
                var bw         = new ZXing.BarcodeWriter();
                var encOptions = new ZXing.Common.EncodingOptions()
                {
                    Margin = 0
                };                                                                      // margin 0 to 1
                bw.Options = encOptions;
                bw.Format  = ZXing.BarcodeFormat.PDF_417;
                var result = new Bitmap(bw.Write(users[i].UserSQNumber));
                result.Save(path + users[i].UserSQNumber, System.Drawing.Imaging.ImageFormat.Png);
                string first = "Employee Code : " + users[i].UserSQNumber;
                string last  = users[i].UserInformationName.ToString() + "\n" + users[i].DesignationName.ToString();
                iTextSharp.text.Paragraph paragraph     = new iTextSharp.text.Paragraph(first, font);
                iTextSharp.text.Paragraph lastparagraph = new iTextSharp.text.Paragraph(last, font);
                paragraph.SetLeading(1.0f, 1.0f);
                lastparagraph.SetLeading(1.0f, 1.0f);
                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(path + users[i].UserSQNumber);
                image.ScaleToFit(new iTextSharp.text.Rectangle(85, 100));
                image.SetAbsolutePosition(0.0f, 0.0f);
                image.PaddingTop = 2;
                PdfPCell cell = new PdfPCell {
                    PaddingLeft = 0, PaddingTop = 2, PaddingBottom = 0, PaddingRight = 0
                };
                // cell.FixedHeight = 60;
                cell.AddElement(paragraph);
                cell.AddElement(image);
                cell.AddElement(lastparagraph);
                cell.Border = 0;
                pdftable.AddCell(cell);
                File.Delete(path + users[i].UserSQNumber);
            }
            doc.Add(pdftable);
            doc.Close();
            resultResponse.isSuccess = true;
            resultResponse.data      = path + fileName + ".pdf";
            return(resultResponse);
        }
Пример #60
0
        public ActionResult GoToViewHoSo(long hoSoId = 0, bool exportExcel = false)
        {
            var hoSo = _hoSoRepos.Get(hoSoId);

            if (hoSo != null)
            {
                if (hoSo.IsCA == true)
                {
                    var    stream    = new MemoryStream();
                    var    outStream = new MemoryStream();
                    byte[] byteInfo  = stream.ToArray();
                    using (iTextSharp.text.Document document = new iTextSharp.text.Document())
                        using (PdfCopy copy = new PdfCopy(document, outStream))
                        {
                            document.Open();
                            string ATTP_FILE_PDF = GetUrlFileDefaut();
                            string filePath      = Path.Combine(ATTP_FILE_PDF, hoSo.DuongDanTepCA);
                            var    fileBytes     = System.IO.File.ReadAllBytes(filePath);
                            copy.AddDocument(new PdfReader(fileBytes));
                        }

                    return(File(outStream.ToArray(), "application/pdf"));
                }
                else
                {
                    //File Template
                    var    xls          = FileHoSo(hoSoId);
                    byte[] fileTemplate = null;
                    using (FlexCel.Render.FlexCelPdfExport pdf = new FlexCel.Render.FlexCelPdfExport())
                    {
                        pdf.Workbook = xls;
                        using (MemoryStream ms = new MemoryStream())
                        {
                            pdf.BeginExport(ms);
                            pdf.ExportAllVisibleSheets(false, "PDF");
                            pdf.EndExport();
                            ms.Position  = 0;
                            fileTemplate = ms.ToArray();
                        }
                    }

                    //Copy List File Đính Kèm
                    string ATTP_FILE_PDF = GetUrlFileDefaut();
                    var    outStream     = new MemoryStream();
                    using (iTextSharp.text.Document document = new iTextSharp.text.Document())
                        using (PdfCopy copy = new PdfCopy(document, outStream))
                        {
                            document.Open();
                            copy.AddDocument(new PdfReader((fileTemplate)));
                        }
                    return(File(outStream.ToArray(), "application/pdf"));
                }
            }
            else
            {
                return(null);
            }
        }