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

Signals that an new page has to be started.
public NewPage ( ) : bool
Результат bool
        protected virtual void WriteTOC(List<PdfContentParameter> contents, PdfWriter writer, Document document)
        {
            document.NewPage();
            PdfPTable t = new PdfPTable(2);
            t.WidthPercentage = 100;
            t.SetWidths(new float[] { 98f, 2f });
            t.TotalWidth = document.PageSize.Width - (document.LeftMargin + document.RightMargin);
            t.AddCell(new PdfPCell(
                new Phrase(GlobalStringResource.TableOfContents,
                    FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 16))
                ) { Colspan = 2, Border = Rectangle.NO_BORDER, PaddingBottom = 25 });

            foreach (PdfContentParameter item in contents)
            {
                if (!string.IsNullOrEmpty(item.Header))
                {
                    t.AddCell(
                        new PdfPCell(
                                new Phrase(item.Header,
                                    FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 8)
                                    )
                            ) { Border = Rectangle.NO_BORDER, NoWrap = false, FixedHeight = 15, }
                        );

                    PdfPCell templateCell = new PdfPCell(Image.GetInstance(item.Template));
                    templateCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                    templateCell.Border = Rectangle.NO_BORDER;
                    t.AddCell(templateCell);
                }
            }
            float docHeight = document.PageSize.Height - heightOffset;
            document.Add(t);
        }
        public override byte[] CreatePdf(List<PdfContentParameter> contents, string[] images, int type)
        {
            var document = new Document();
            float docHeight = document.PageSize.Height - heightOffset;
            document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
            document.SetMargins(50, 50, 10, 40);

            var output = new MemoryStream();
            var writer = PdfWriter.GetInstance(document, output);

            writer.PageEvent = new HeaderFooterHandler(type);

            document.Open();

            document.Add(contents[0].Table);

            for (int i = 0; i < images.Length; i++)
            {
                document.NewPage();
                float subtrahend = document.PageSize.Height - heightOffset;
                iTextSharp.text.Image pool = iTextSharp.text.Image.GetInstance(images[i]);
                pool.Alignment = 3;
                pool.ScaleToFit(document.PageSize.Width - (document.RightMargin * 2), subtrahend);
                //pool.ScaleAbsolute(document.PageSize.Width - (document.RightMargin * 2), subtrahend);
                document.Add(pool);
            }

            document.Close();
            return output.ToArray();
        }
        private void CreatePdf(FileStream outputStream)
        {
            var doc = new Document(PageSize.A4);

            PdfWriter.GetInstance(doc, outputStream);

            doc.Open();

            WriteFrontPage(doc);
            doc.NewPage();
            WriteSpecification(doc);

            foreach (var representation in _report.Representations)
            {
                doc.NewPage();
                doc.Add(new Paragraph("Representation"));
            }

            PdfPTable table = new PdfPTable(2);
            table.AddCell(new PdfPCell { Colspan = 1 });
            PdfPCell cell = new PdfPCell { Colspan = 1, HorizontalAlignment = 1, Phrase = new Phrase("REPRESENTATIONSKOSTNADER") };
            table.AddCell(cell);
            table.AddCell("Col 1 Row 1");
            table.AddCell("Col 2 Row 1");
            table.AddCell("Col 3 Row 1");
            table.AddCell("Col 1 Row 2");
            table.AddCell("Col 2 Row 2");
            table.AddCell("Col 3 Row 2");
            doc.Add(table);
            doc.Close();
        }
Пример #4
1
        public static byte[] MergePdfs(IEnumerable<byte[]> inputFiles)
        {
            MemoryStream outputStream = new MemoryStream();
            Document document = new Document();
            PdfWriter writer = PdfWriter.GetInstance(document, outputStream);
            document.Open();
            PdfContentByte content = writer.DirectContent;

            foreach (byte[] input in inputFiles)
            {
                PdfReader reader = new PdfReader(input);
                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    document.SetPageSize(reader.GetPageSizeWithRotation(i));
                    document.NewPage();
                    PdfImportedPage page = writer.GetImportedPage(reader, i);
                    int rotation = reader.GetPageRotation(i);
                    if (rotation == 90 || rotation == 270)
                    {
                        content.AddTemplate(page, 0, -1f, 1f, 0, 0,
                            reader.GetPageSizeWithRotation(i).Height);
                    }
                    else
                    {
                        content.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                    }
                }
            }

            document.Close();

            return outputStream.ToArray();
        }
Пример #5
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);
        }
Пример #6
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;
        }
Пример #7
0
 // ---------------------------------------------------------------------------    
 /**
  * Creates a PDF document for PdfReader.
  */
 public byte[] CreatePdf()
 {
     using (MemoryStream ms = new MemoryStream())
     {
         // step 1
         using (Document document = new Document(PageSize.POSTCARD, 30, 30, 30, 30))
         {
             // step 2
             PdfWriter writer = PdfWriter.GetInstance(document, ms);
             // step 3
             document.Open();
             // step 4
             PdfContentByte under = writer.DirectContentUnder;
             // page 1: rectangle
             under.SetRGBColorFill(0xFF, 0xD7, 0x00);
             under.Rectangle(5, 5,
                 PageSize.POSTCARD.Width - 10, PageSize.POSTCARD.Height - 10);
             under.Fill();
             document.NewPage();
             // page 2: image
             Image img = Image.GetInstance(Path.Combine(
               Utility.ResourceImage, "loa.jpg"
             ));
             img.SetAbsolutePosition(
               (PageSize.POSTCARD.Width - img.ScaledWidth) / 2,
               (PageSize.POSTCARD.Height - img.ScaledHeight) / 2
             );
             document.Add(img);
             document.NewPage();
             // page 3: the words "Foobar Film Festival"
             Paragraph p = new Paragraph(
               "Foobar Film Festival", new Font(Font.FontFamily.HELVETICA, 22)
             );
             p.Alignment = Element.ALIGN_CENTER;
             document.Add(p);
             document.NewPage();
             // page 4: the words "SOLD OUT"
             PdfContentByte over = writer.DirectContent;
             over.SaveState();
             float sinus = (float)Math.Sin(Math.PI / 60);
             float cosinus = (float)Math.Cos(Math.PI / 60);
             BaseFont bf = BaseFont.CreateFont();
             over.BeginText();
             over.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
             over.SetLineWidth(1.5f);
             over.SetRGBColorStroke(0xFF, 0x00, 0x00);
             over.SetRGBColorFill(0xFF, 0xFF, 0xFF);
             over.SetFontAndSize(bf, 36);
             over.SetTextMatrix(cosinus, sinus, -sinus, cosinus, 50, 324);
             over.ShowText("SOLD OUT");
             over.SetTextMatrix(0, 0);
             over.EndText();
             over.RestoreState();
         }
         return ms.ToArray();
     }
 }
Пример #8
0
 // ===========================================================================
 public void Write(Stream stream)
 {
     // step 1
     using (Document document = new Document(PageSize.A4.Rotate()))
     {
         // step 2
         PdfWriter writer = PdfWriter.GetInstance(document, stream);
         // step 3
         document.Open();
         // step 4
         ColumnText column = new ColumnText(writer.DirectContent);
         List<string> days = PojoFactory.GetDays();
         // COlumn definition
         float[][] x = {
   new float[] { document.Left, document.Left + 380 },
   new float[] { document.Right - 380, document.Right }
 };
         // Loop over the festival days
         foreach (string day in days)
         {
             // add content to the column
             column.AddElement(GetTable(day));
             int count = 0;
             float height = 0;
             // iText-ONLY, 'Initial value of the status' => 0
             // iTextSharp **DOES NOT** include this member variable
             // int status = ColumnText.START_COLUMN;
             int status = 0;
             // render the column as long as it has content
             while (ColumnText.HasMoreText(status))
             {
                 // add the top-level header to each new page
                 if (count == 0)
                 {
                     height = AddHeaderTable(document, day, writer.PageNumber);
                 }
                 // set the dimensions of the current column
                 column.SetSimpleColumn(
                   x[count][0], document.Bottom,
                   x[count][1], document.Top - height - 10
                 );
                 // render as much content as possible
                 status = column.Go();
                 // go to a new page if you've reached the last column
                 if (++count > 1)
                 {
                     count = 0;
                     document.NewPage();
                 }
             }
             document.NewPage();
         }
     }
 }
Пример #9
0
        public static void CombinePicturesToPdf(List <string> pictures, string folder, string name)
        {
            float x = Image.GetInstance(pictures[0]).Width;
            float y = 14400;

            Rectangle pageSize = new Rectangle(x, y);

            iTextSharp.text.Document document = new iTextSharp.text.Document(pageSize, 0, 0, 0, 0);

            try
            {
                iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(folder + @"\" + name + ".pdf", FileMode.Create, FileAccess.ReadWrite));
                document.Open();
                Image image;

                document.NewPage();

                for (int i = 0; i < pictures.Count; i++)
                {
                    if (string.IsNullOrEmpty(pictures[i]))
                    {
                        break;
                    }

                    image           = Image.GetInstance(pictures[i]);
                    image.Alignment = Image.ALIGN_MIDDLE;

                    if (y + image.Height > 14400)
                    {
                        y = 0;
                        document.NewPage();
                        document.Add(image);
                    }
                    else
                    {
                        y += image.Height;
                        document.Add(image);
                    }
                }

                Console.WriteLine("转换成功!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("转换失败,原因:" + ex.Message);
            }

            document.Close();
        }
Пример #10
0
        private void CreatePdf(string[] tiffImages, string outputFile)
        {
            Document    document    = new Document();
            PdfWriter   writer      = PdfWriter.GetInstance(document, new System.IO.FileStream(outputFile, System.IO.FileMode.Create));

            document.Open();

            for (int count = 0; count < tiffImages.Length; count++)
            {
                Bitmap  bitmap  = new Bitmap(tiffImages[count]);
                int     total   = bitmap.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);

                PdfContentByte cb = writer.DirectContent;

                for (int k = 0; k < total; ++k)
                {
                    bitmap.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k);
                    Image image = Image.GetInstance(bitmap, System.Drawing.Imaging.ImageFormat.Bmp);

                    image.ScalePercent(72f / image.DpiX * 100);
                    image.SetAbsolutePosition(0, 0);
                    cb.AddImage(image);
                    document.NewPage();
                }
            }
            UpdateProperties(document);
            document.Close();
        }
Пример #11
0
        /// <summary>
        /// Add a page that includes a bullet list.
        /// </summary>
        /// <param name="doc"></param>
        private void AddPageWithBulletList(iTextSharp.text.Document doc)
        {
            // Add a new page to the document
            doc.NewPage();

            // The header at the top of the page is an anchor linked to by the table of contents.
            iTextSharp.text.Anchor contentsAnchor = new iTextSharp.text.Anchor("RESEARCH\n\n", _largeFont);
            contentsAnchor.Name = "research";

            // Add the header anchor to the page
            this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, contentsAnchor);

            // Create an unordered bullet list.  The 10f argument separates the bullet from the text by 10 points
            iTextSharp.text.List list = new iTextSharp.text.List(iTextSharp.text.List.UNORDERED, 10f);
            list.SetListSymbol("\u2022");   // Set the bullet symbol (without this a hypen starts each list item)
            list.IndentationLeft = 20f;     // Indent the list 20 points
            list.Add(new iTextSharp.text.ListItem("Lift, thrust, drag, and gravity are the four forces that act on a plane.", _standardFont));
            list.Add(new iTextSharp.text.ListItem("A plane should be light to help fight against gravity's pull to the ground.", _standardFont));
            list.Add(new iTextSharp.text.ListItem("Gravity will have less effect on a plane built from the lightest materials available.", _standardFont));
            list.Add(new iTextSharp.text.ListItem("In order to fly well, airplanes must be stable.", _standardFont));
            list.Add(new iTextSharp.text.ListItem("A plane that is unstable will either pitch up into a stall, or nose-dive.", _standardFont));
            doc.Add(list);  // Add the list to the page

            // Add some white space and another heading
            this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, new Chunk("\n\n\nHYPOTHESIS\n\n"));

            // Add some final text to the page
            this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk("Given five paper airplanes made out of newspaper, printer paper, construction paper, paper towel, and posterboard, the airplane made out of printer paper will fly the furthest."));
        }
Пример #12
0
        private PdfReader GetPdf(ICollection <byte[]> pages)
        {
            if (pages == null || pages.Count() == 0)
            {
                return(null);
            }

            MemoryStream streamOut = new MemoryStream();
            PdfReader    reader    = null;

            using (its.Document doc = new its.Document(iTextSharp.text.PageSize.A4, -70, -70, 0, 0))
            {
                PdfWriter.GetInstance(doc, streamOut);
                doc.Open();

                foreach (byte[] page in pages)
                {
                    iTextSharp.text.Image image = its.Image.GetInstance(page);
                    doc.NewPage();
                    PdfPTable table = new PdfPTable(1);
                    table.AddCell(new PdfPCell(image));
                    doc.Add(table);
                }
                doc.Close();
                doc.Dispose();
                reader = new PdfReader(streamOut.ToArray());
            }
            return(reader);
        }
        public void Test() {
            String file = "tagged_pdf_page_events.pdf";

            Document document = new Document();

            PdfWriter pdfWriter = PdfWriter.GetInstance(document, new FileStream(OUTPUT_FOLDER + file, FileMode.Create));

            pdfWriter.SetTagged();
            pdfWriter.PageEvent = new TaggedPdfPageEventsTest();

            document.Open();

            document.Add(new Paragraph("Hello"));
            document.NewPage();
            document.Add(new Paragraph("World"));

            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);
            }
        }
Пример #14
0
// ---------------------------------------------------------------------------        
    public override void Write(Stream stream) {
      // step 1
      using (Document document = new Document(PageSize.A4.Rotate())) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        writer.CompressionLevel = 0;
        // step 3
        document.Open();
        // step 4
        PdfContentByte over = writer.DirectContent;
        PdfContentByte under = writer.DirectContentUnder;
        locations = PojoFactory.GetLocations();
        List<string> days = PojoFactory.GetDays();
        List<Screening> screenings;
        foreach (string day in days) {
          DrawTimeTable(under);
          DrawTimeSlots(over);
          screenings = PojoFactory.GetScreenings(day);
          foreach (Screening screening in screenings) {
            DrawBlock(screening, under, over);
          }
          document.NewPage();
        }
      }
    }
Пример #15
0
        /// <summary>
        /// 合并PDF文件
        /// </summary>
        /// <param name="originalFilePath">原始文件地址</param>
        /// <param name="mergeFilePath">合并文件地址</param>
        /// <param name="newFilePath">生成文件地址</param>
        private void MergePdf(string originalFilePath, string mergeFilePath, string newFilePath)
        {
            string[]         fileList   = { originalFilePath, mergeFilePath };
            List <PdfReader> readerList = new List <PdfReader>();
            PdfReader        reader     = null;

            iTextSharp.text.Rectangle rec      = new iTextSharp.text.Rectangle(1660, 1000);
            iTextSharp.text.Document  document = new iTextSharp.text.Document(rec);
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(newFilePath, FileMode.Create));

            document.Open();
            PdfContentByte  cb = writer.DirectContent;
            PdfImportedPage newPage;

            foreach (var item in fileList)
            {
                reader = new PdfReader(item);
                int iPageNum = reader.NumberOfPages;
                for (int j = 1; j <= iPageNum; j++)
                {
                    document.NewPage();
                    newPage = writer.GetImportedPage(reader, j);
                    cb.AddTemplate(newPage, 0, 0);
                }
                readerList.Add(reader);
            }
            document.Close();
            foreach (var item in readerList)
            {
                item.Dispose();
            }
        }
        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();
        }
Пример #17
0
        void WriteAlgorithmBenchmark(iTextSharp.text.Document doc, ISearchAlgorithm <string> algorithm, SearchReport <string> report)
        {
            iTextSharp.text.pdf.draw.LineSeparator line = new iTextSharp.text.pdf.draw.LineSeparator(1f, 100f, iTextSharp.text.BaseColor.BLACK, iTextSharp.text.Element.ALIGN_CENTER, -1);
            iTextSharp.text.Chunk linebreak             = new iTextSharp.text.Chunk(line);
            Chunk c = new Chunk(algorithm.Name, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 24, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLUE));

            c.SetGenericTag(algorithm.Name);
            doc.Add(new Paragraph(c));
            // algorithm description
            Chunk desc = new Chunk(algorithm.Description, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.ITALIC, iTextSharp.text.BaseColor.BLACK));

            doc.Add(new Paragraph(desc));
            // algorithm benchmark
            Chunk time = new Chunk("The algorithm took " + report.ElapsedTime + " to find the goal.", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.BOLDITALIC, iTextSharp.text.BaseColor.BLACK));

            doc.Add(new Paragraph(time));

            // path
            time = new Chunk("The result path costs " + algorithm.CalculateCost(report.Result), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, 12, iTextSharp.text.Font.BOLDITALIC, iTextSharp.text.BaseColor.BLACK));
            doc.Add(new Paragraph(time));
            // write steps
            foreach (var step in report.Steps)
            {
                WriteAlgorithmStep(doc, step.StepInformation, step.GraphCapture);
            }

            doc.NewPage();
        }
Пример #18
0
 private void SpremanjePDFa()
 {
     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 Paragraph("OBRACUNSKE LISTE"));
                 foreach (ObracunskaLista o in ObracunskeListe)
                 {
                     doc.NewPage();
                     doc.Add(new Paragraph(o.ToString()));
                 }
             }
             catch (Exception ex)
             {
                 MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
             finally
             {
                 doc.Close();
             }
         }
     }
 }
Пример #19
0
// ===========================================================================
    public override void Write(Stream stream) {
      float w = PageSize.A4.Width;
      float h = PageSize.A4.Height;
      Rectangle rect = new Rectangle(-2*w, -2*h, 2*w, 2*h);
      Rectangle crop = new Rectangle(-2 * w, h, -w, 2 * h);      
      // step 1
      using (Document document = new Document(rect)) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        writer.CropBoxSize = crop;
        // step 3
        document.Open();
        // step 4
        PdfContentByte content = writer.DirectContent;
        PdfTemplate template = CreateTemplate(content, rect, 4);
        float adjust;
        while(true) {
          content.AddTemplate(template, -2*w, -2*h);
          adjust = crop.Right + w;
          if (adjust > 2 * w) {
            adjust = crop.Bottom - h;
            if (adjust < - 2 * h)
                break;
            crop = new Rectangle(-2*w, adjust, -w, crop.Bottom);
          }
          else {
            crop = new Rectangle(crop.Right, crop.Bottom, adjust, crop.Top);
          }
          writer.CropBoxSize = crop;
          document.NewPage();
        }
      }
    }
Пример #20
0
 // ===========================================================================
 public void Write(Stream stream)
 {
     // step 1
     using (Document document = new Document())
     {
         // step 2
         PdfWriter writer = PdfWriter.GetInstance(document, stream);
         // step 3
         document.Open();
         // step 4
         // Create a table and fill it with movies
         IEnumerable<Movie> movies = PojoFactory.GetMovies(3);
         PdfPTable table = new PdfPTable(new float[] { 1, 5, 5, 1 });
         foreach (Movie movie in movies)
         {
             table.AddCell(movie.Year.ToString());
             table.AddCell(movie.MovieTitle);
             table.AddCell(movie.OriginalTitle);
             table.AddCell(movie.Duration.ToString());
         }
         // set the total width of the table
         table.TotalWidth = 600;
         PdfContentByte canvas = writer.DirectContent;
         // draw the first three columns on one page
         table.WriteSelectedRows(0, 2, 0, -1, 236, 806, canvas);
         document.NewPage();
         // draw the next three columns on the next page
         table.WriteSelectedRows(2, -1, 0, -1, 36, 806, canvas);
     }
 }
        private static void WritePage(PdfReader reader, iTextSharp.text.Document document, PdfWriter writer)
        {
            try
            {
                PdfContentByte  cb = writer.DirectContent;
                PdfImportedPage page;

                int rotation = 0;

                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    document.SetPageSize(reader.GetPageSizeWithRotation(i));
                    document.NewPage();

                    page = writer.GetImportedPage(reader, i);

                    rotation = reader.GetPageRotation(i);

                    if (rotation == 90 || rotation == 270)
                    {
                        cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                    }
                    else
                    {
                        cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("An Error occurred");
            }
        }
Пример #22
0
        public static String Merge(String[] pdfs)
        {
            String tempFilePath = GetTemporaryFile();

            Document document = new Document();
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(tempFilePath, FileMode.Create));

            document.Open();

            PdfContentByte content = writer.DirectContent;
            document.NewPage();

            foreach (String file in pdfs)
            {
                PdfReader reader = new PdfReader(file);
                int numberOfPages = reader.NumberOfPages;

                for (int i = 1; i <= numberOfPages; i++)
                {
                    PdfImportedPage page = writer.GetImportedPage(reader, i);
                    // page, horizontal scaling, x, rotation, vertical scaling, horizontal offset, vertical offset
                    content.AddTemplate(page, 1, 0, 0, 1, 0.0f, 200.0f);
                    //content.AddTemplate(page);
                }
            }

            document.Close();

            return tempFilePath;
        }
Пример #23
0
        public bool GraphConvertPdf(string savename,string savepath,string basepath,string basetype)
        {
            bool flag = true;
            Document doc = new Document();

            savename = PdfClass.PdfFileNameConverter(savename);
            try
            {
                PdfWriter.GetInstance(doc, new FileStream(@savepath + "\\" + savename + ".pdf", FileMode.Create));

                doc.Open();

                int max = Directory.GetFiles(@basepath).Count();
                for (int i = 0; i < max; i++)
                {
                    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(new Uri(@basepath + "\\" + i.ToString() + "." + basetype));
                    iTextSharp.text.Rectangle pagesize = new iTextSharp.text.Rectangle(image.Width / image.DpiX * 25.4f * 2.834f, image.Height / image.DpiY * 25.4f * 2.834f);

                    doc.SetPageSize(pagesize);
                    image.ScaleToFit(doc.PageSize.Width, doc.PageSize.Height);
                    image.SetAbsolutePosition(0f, 0f);

                    doc.NewPage();
                    doc.Add(image);

                }
                doc.Close();
            }
            catch
            {
                flag = false;
            }

            return flag;
        }
Пример #24
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);
     }
 }
Пример #25
0
        /// <summary>多个图片合并成Pdf</summary>
        /// <param name="filesimg">图片流集合</param>
        /// <returns></returns>
        public byte[] imgPdfcreate(List <Byte[]> filesimg)
        {
            MemoryStream outputStream = new MemoryStream();

            iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 25, 25, 25, 25);
            try
            {
                PdfWriter writer = PdfWriter.GetInstance(document, outputStream);
                document.Open();
                iTextSharp.text.Image image;
                for (int i = 0; i < filesimg.Count; i++)
                {
                    image = iTextSharp.text.Image.GetInstance(filesimg[i]);
                    image.SetAbsolutePosition(0, 0); //'设置图片的位置在0.0
                                                     // image.ScaleAbsolute(PageSize.A4);
                                                     // image.ScaleAbsolute(PageSize.A4); image.ScaleAbsolute(PageSize.A4);//'设置图片大小为A4纸大小
                    document.NewPage();
                    document.Add(image);
                }
                document.Close();
                outputStream.Close();
                return(outputStream.ToArray());
            }
            catch (Exception ex)
            {
                document.Close();
                outputStream.Close();
                return(null);
            }
        }
Пример #26
0
        private void button6_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Filter = "PDF|*.pdf";
            string filePath = "";

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                filePath = sfd.FileName;
                iTextSharp.text.Document _pdfDocument = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10, 10, 25, 25);

                PdfWriter.GetInstance(_pdfDocument, new FileStream(filePath, FileMode.Create));
                _pdfDocument.Open();
                // First page
                _pdfDocument.Add(new iTextSharp.text.Paragraph(content[0]));
                // for each other page
                // add a page
                for (int i = 1; i < content.Count; i++)
                {
                    _pdfDocument.NewPage();
                    _pdfDocument.Add(new iTextSharp.text.Paragraph(content[i]));
                }

                // _pdfDocument.NewPage();
                _pdfDocument.Close();
            }
        }
        /// <summary>
        /// Add a page that includes a bullet list.
        /// </summary>
        /// <param name="doc"></param>
        private void AddPageWithBulletList(iTextSharp.text.Document doc)
        {
            // Add a new page to the document
            doc.NewPage();

            // The header at the top of the page is an anchor linked to by the table of contents.
            iTextSharp.text.Anchor contentsAnchor = new iTextSharp.text.Anchor("Beginning page\n\n", _largeFont);
            contentsAnchor.Name = "start";

            // Add the header anchor to the page
            this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, contentsAnchor);

            // Create an unordered bullet list.  The 10f argument separates the bullet from the text by 10 points
            iTextSharp.text.List list = new iTextSharp.text.List(iTextSharp.text.List.UNORDERED, 10f);
            list.SetListSymbol("\u2022");   // Set the bullet symbol (without this a hypen starts each list item)
            list.IndentationLeft = 20f;     // Indent the list 20 points
            list.Add(new ListItem("Print document", _standardFont));
            list.Add(new ListItem("Route to mail room", _standardFont));
            list.Add(new ListItem("Route to accounting", _standardFont));
            list.Add(new ListItem("Check approval", _standardFont));
            list.Add(new ListItem("Send the check", _standardFont));
            doc.Add(list);  // Add the list to the page

            // Add some white space and another heading
            this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, new Chunk("\n\n\n"));
            this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, new Chunk("Error condition\n\n"));

            // Add some final text to the page
            this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, _standardFont, new Chunk("In case of error, check will be manually approved"));
        }
Пример #28
0
        public static void ConvertFirstApproach()
        {
            // creation of the document with a certain size and certain margins
            iTextSharp.text.Document document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);

            // creation of the different writers
            iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(@"C:\Users\Mohd\Documents\visual studio 2013\Projects\TiffToPDF\TiffToPDF\tiff.tif.pdf", System.IO.FileMode.Create));

            // load the tiff image and count the total pages
            System.Drawing.Bitmap bm = new System.Drawing.Bitmap(@"C:\Users\Mohd\Documents\visual studio 2013\Projects\TiffToPDF\TiffToPDF\tiff.tif");
            int total = bm.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page);

            document.Open();
            iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
            for (int k = 0; k < total; ++k)
            {
                bm.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k);

                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bm, ImageFormat.Jpeg);
                img.SetAbsolutePosition(0, 0);
                img.ScaleAbsolute(500, 500);
                //  img.ScalePercent(72f / img.DpiX * 100);
                img.ScaleAbsoluteHeight(document.PageSize.Height);
                img.ScaleAbsoluteWidth(document.PageSize.Width);
                //    img.CompressionLevel = 1;
                //    img.Deflated = true;
                cb.AddImage(img);

                document.NewPage();
            }
            document.Close();
        }
Пример #29
0
        /// <summary>
        /// Add a page that includes a bullet list.
        /// </summary>
        /// <param name="doc"></param>
        private void AddPageWithBulletList(iTextSharp.text.Document doc, List <string> data, string listName, string warningMessage)
        {
            // Add a new page to the document
            doc.NewPage();

            // The header at the top of the page is an anchor linked to by the table of contents.
            iTextSharp.text.Anchor contentsAnchor = new iTextSharp.text.Anchor(listName, this.largeFont);
            contentsAnchor.Name = "research";

            // Add the header anchor to the page
            this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, this.largeFont, contentsAnchor);

            // Create an unordered bullet list.  The 10f argument separates the bullet from the text by 10 points
            iTextSharp.text.List list = new iTextSharp.text.List(iTextSharp.text.List.UNORDERED, 10f);
            list.SetListSymbol("\u2022");   // Set the bullet symbol (without this a hypen starts each list item)
            list.IndentationLeft = 20f;     // Indent the list 20 points

            foreach (var emp in data)
            {
                list.Add(new ListItem(emp, this.standardFont));
            }

            doc.Add(list);  // Add the list to the page

            // Add some white space and another heading
            this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, this.largeFont, new Chunk("\n\n\n"));
            this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, this.largeFont, new Chunk("WARNING (!)\n\n"));

            // Add some final text to the page
            this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_LEFT, this.standardFont, new Chunk(warningMessage));
        }
Пример #30
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);
            }
        }
Пример #31
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);
                }
                //}
            }
        }
Пример #32
0
        /// <summary>
        /// Add a page containing a single image.  Set the page size to match the image size.
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="imagePath"></param>
        private void AddPageWithImage(iTextSharp.text.Document doc, String imagePath)
        {
            // Read the image file
            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(new Uri(imagePath));

            // Set the page size to the dimensions of the image BEFORE adding a new page to the document.
            // Pad the height a bit to leave room for the page header.
            float imageWidth  = image.Width;
            float imageHeight = image.Height;

            doc.SetMargins(0, 0, 0, 0);
            doc.SetPageSize(new iTextSharp.text.Rectangle(imageWidth, imageHeight + 100));

            // Add a new page
            doc.NewPage();

            // The header at the top of the page is an anchor linked to by the table of contents.
            iTextSharp.text.Anchor contentsAnchor = new iTextSharp.text.Anchor("\nGRAPH\n\n", _largeFont);
            contentsAnchor.Name = "graph";

            // Add the anchor and image to the page
            this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont, contentsAnchor);
            doc.Add(image);
            image = null;
        }
Пример #33
0
    public iTextSharp.text.Document faturalariGetir()
    {
        iTextSharp.text.Document pdf = null;
        DataTable dt = db.exReaderDT(CommandType.Text, "select ca.cari_vergiDairesi,ca.cari_vergiNo, ca.cari_unvan,ca.cari_adres, ch.chh_tarihi,sum(ch.chh_aratoplam) as aratoplam,sum(ch.chh_ft_kdv) as kdv,sum(ch.chh_geneltoplam) as geneltoplam,ch.chh_evrakno_sira from cari_hesap_hareketleri ch,cariler ca where ca.cari_kodu=ch.chh_cari_kodu and ch.chh_evrakno_sira in(select distinct(chh_evrakno_sira) from cari_hesap_hareketleri where chh_evrakno_sira>=@evrakno1 and chh_evrakno_sira<=@evrakno2) group by chh_evrakno_sira,chh_cari_kodu,chh_tarihi,cari_unvan,cari_adres,ca.Cari_VergiDairesi,ca.cari_vergiNO", "evrakno1=" + Request.QueryString["evrakno1"].ToString() + ",evrakno2=" + Request.QueryString["evrakno2"]);

        if (dt != null && dt.Rows.Count > 0)
        {
            myList lst = pdfOlustur();
            pdf = lst.pdf;
            PdfWriter writer = lst.writer;
            int       sayac  = 0;
            foreach (DataRow item in dt.Rows)
            {
                if (sayac > 0)
                {
                    pdf.NewPage();
                }
                PdfPTable tblUst = ustTableGetir(item["cari_unvan"].ToString(), item["cari_adres"].ToString(), item["chh_tarihi"].ToString().Split(' ')[0], item["chh_evrakno_sira"].ToString(), item["cari_vergiDairesi"].ToString(), item["cari_vergiNo"].ToString());
                pdf.Open();
                pdf.Add(tblUst);
                PdfPTable tblSatirlar = fatura_bagla(item["chh_evrakno_sira"].ToString());
                if (tblSatirlar != null)
                {
                    pdf.Add(tblSatirlar);
                }
                PdfPTable tblAltSatir = footerTableGEtir((float)Convert.ToDouble(item["aratoplam"]), (float)Convert.ToDouble(item["kdv"]), (float)Convert.ToDouble(item["geneltoplam"]));
                tblAltSatir.WriteSelectedRows(0, -1, (int)((pdf.PageSize.Width - tblAltSatir.TotalWidth) / 2), (pdf.Bottom + 65), writer.DirectContent);
                sayac++;
            }
            pdf.Close();
        }
        return(pdf);
    }
        /// <summary>
        /// Add a blank page to the document.
        /// </summary>
        /// <param name="doc"></param>
        private void AddPageWithInternalLinks(iTextSharp.text.Document doc)
        {
            // Generate links to be embedded in the page
            Anchor startAnchor = new Anchor("Beginning words.....\n\n", _standardFont);

            startAnchor.Reference = "#start"; // this link references a named anchor within the document
            Anchor graphAnchor = new Anchor("Graph\n\n", _standardFont);

            graphAnchor.Reference = "#graph";
            Anchor endAnchor = new Anchor("Ending words....", _standardFont);

            endAnchor.Reference = "#end";

            // Add a new page to the document
            doc.NewPage();

            // Add heading text to the page
            this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _largeFont,
                              new iTextSharp.text.Chunk("TABLE OF CONTENTS\n\n\n\n\n"));

            // Add the links to the page
            this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _standardFont, startAnchor);
            this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _standardFont, graphAnchor);
            this.AddParagraph(doc, iTextSharp.text.Element.ALIGN_CENTER, _standardFont, endAnchor);
        }
Пример #35
0
        public void AddPdf(string sInFilePath, ref iTextSharp.text.Document oPdfDoc, ref PdfWriter oPdfWriter)
        {
            iTextSharp.text.pdf.PdfContentByte oDirectContent = oPdfWriter.DirectContent;
            iTextSharp.text.pdf.PdfReader      oPdfReader     = new iTextSharp.text.pdf.PdfReader(sInFilePath);
            int iNumberOfPages = oPdfReader.NumberOfPages;
            int iPage          = 0;

            while ((iPage < iNumberOfPages))
            {
                iPage += 1;

                int iRotation = oPdfReader.GetPageRotation(iPage);
                iTextSharp.text.pdf.PdfImportedPage oPdfImportedPage = oPdfWriter.GetImportedPage(oPdfReader, iPage);
                oPdfDoc.SetPageSize(oPdfReader.GetPageSizeWithRotation(iPage));
                oPdfDoc.NewPage();

                if ((iRotation == 90) | (iRotation == 270))
                {
                    oDirectContent.AddTemplate(oPdfImportedPage, 0, -1f, 1f, 0, 0, oPdfReader.GetPageSizeWithRotation(iPage).Height);
                }
                else
                {
                    oDirectContent.AddTemplate(oPdfImportedPage, 1f, 0, 0, 1f, 0, 0);
                }
            }
        }
Пример #36
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();
        }
      }
    }
Пример #37
0
        public static void Watermark(string inputPath, string outputPath, string watermarkPath)
        {
            try
            {
                PdfReader reader = new PdfReader(inputPath);

                iTextSharp.text.Document document = new iTextSharp.text.Document();
                FileStream fs     = new FileStream(outputPath, FileMode.OpenOrCreate);
                PdfWriter  writer = PdfWriter.GetInstance(document, fs);
                document.Open();
                var imagewatermark = iTextSharp.text.Image.GetInstance(watermarkPath);
                document.Add(imagewatermark);
                document.Open();
                PdfContentByte  cb = writer.DirectContent;
                PdfImportedPage newPage;
                int             iPageNum = reader.NumberOfPages;
                for (int j = 1; j <= iPageNum; j++)
                {
                    document.NewPage();
                    newPage = writer.GetImportedPage(reader, j);
                    cb.AddTemplate(newPage, 0, 0);
                }
                document.Close();
                writer.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                // WriteLog.Log(ex.ToString());
                throw ex;
            }
        }
Пример #38
0
        public string ExportToPdfAsBase64String(IEnumerable<System.Drawing.Image> imageFiles)
        {
            var result = "";
            using (var pdfDoc = new Document(PdfPageSize))
            {
                using (var stream = new MemoryStream())
                {
                    var pdfWriter = PdfWriter.GetInstance(pdfDoc, stream);

                    pdfWriter.SetPdfVersion(new PdfName("1.5"));
                    pdfWriter.CompressionLevel = PdfStream.BEST_COMPRESSION;

                    pdfDoc.Open();

                    foreach (var img in imageFiles.Select(bmpImage => Image.GetInstance(bmpImage, ImageFormat.Bmp)))
                    {
                        if (FitImagesToPage)
                        {
                            img.ScaleAbsolute(pdfDoc.PageSize.Width, pdfDoc.PageSize.Height);
                        }
                        img.SetAbsolutePosition(0, 0);

                        pdfDoc.Add(img);
                        pdfDoc.NewPage();
                    }

                    result = Convert.ToBase64String(stream.ToArray());
                }

            }
            return result;
        }
        /*public MemoryStream Process(IEnumerable<Student> students)
        {

        }*/
        public MemoryStream Process(IEnumerable<ClassEnrollment> enrollments)
        {
            //Loop through each enrollment to process one report card per student
            var pdfReaders = enrollments.Select(enrollment => new PdfReader(Process(enrollment, enrollment.StudentGrades.ToList()).ToArray())).ToList();

            //Now merge all the pdf streams into one document
            var outputStream = new MemoryStream();
            var pdfDoc = new Document();
            pdfDoc.SetMargins(0, 0, 0, 0);
            var writer = PdfWriter.GetInstance(pdfDoc, outputStream);
            pdfDoc.Open();
            var pdfContentByte = writer.DirectContent;

            foreach (var reader in pdfReaders)
            {
                for (var page = 1; page <= reader.NumberOfPages; page++)
                {
                    var importedPage = writer.GetImportedPage(reader, page);
                    pdfDoc.SetPageSize(importedPage.BoundingBox);
                    pdfDoc.NewPage();
                    pdfContentByte.AddTemplate(importedPage, 0, 0);
                }
            }

            outputStream.Flush();
            pdfDoc.Close();
            outputStream.Close();

            return outputStream;
        }
Пример #40
0
        public MemoryStream Render(IEnumerable<Page> pages, Unit pageWidth, Unit pageHeight)
        {
            var currentPageNumber = 1;

            var document = new Document(new Rectangle((float) pageWidth.Points, (float) pageHeight.Points));

            var memoryStream = new MemoryStream();
            var writer = PdfWriter.GetInstance(document, memoryStream);
            document.Open();
            foreach (var page in pages)
            {
                foreach (var element in page.Elements)
                {
                    borderRenderer.Render(writer, element);

                    if (element.Specification is Backgrounded)
                        backgroundRenderer.Render(writer, element);

                    if (element.Specification is Imaged)
                        imageRenderer.Render(writer, element);

                    if (element.Specification is Texted)
                        textRenderer.Render(writer, element);
                }
                currentPageNumber++;
                document.NewPage();
            }

            document.Close();
            return memoryStream;
        }
Пример #41
0
// ---------------------------------------------------------------------------         
    public void Write(Stream stream) {
      // Creating a reader
      string resource = Path.Combine(Utility.ResourcePdf, RESOURCE);
      PdfReader reader = new PdfReader(resource);
      Rectangle pagesize = reader.GetPageSizeWithRotation(1); 
      using (ZipFile zip = new ZipFile()) {
        // step 1
        using (MemoryStream ms = new MemoryStream()) {
          using (Document document = new Document(pagesize)) {
            // step 2
            PdfWriter writer = PdfWriter.GetInstance(document, ms);
            // step 3
            document.Open();
            // step 4
            PdfContentByte content = writer.DirectContent;
            PdfImportedPage page = writer.GetImportedPage(reader, 1);
            // adding the same page 16 times with a different offset
            float x, y;
            for (int i = 0; i < 16; i++) {
              x = -pagesize.Width * (i % 4);
              y = pagesize.Height * (i / 4 - 3);
              content.AddTemplate(page, 4, 0, 0, 4, x, y);
              document.NewPage();
            }
          }
          zip.AddEntry(RESULT, ms.ToArray());
        }
        zip.AddFile(resource, "");
        zip.Save(stream);
      }
    }
// ===========================================================================
    public override void Write(Stream stream) {
      // step 1
      using (Document document = new Document()) {
        // step 2
        PdfWriter writer = PdfWriter.GetInstance(document, stream);
        // step 3
        document.Open();
        // step 4
        PdfContentByte canvas = writer.DirectContent;
        PdfShading axial = PdfShading.SimpleAxial(writer, 36, 716, 396,
          788, BaseColor.ORANGE, BaseColor.BLUE
        );
        canvas.PaintShading(axial);
        document.NewPage();
        PdfShading radial = PdfShading.SimpleRadial(writer,
          200, 700, 50, 300, 700, 100,
          new BaseColor(0xFF, 0xF7, 0x94),
          new BaseColor(0xF7, 0x8A, 0x6B),
          false, false
        );
        canvas.PaintShading(radial);

        PdfShadingPattern shading = new PdfShadingPattern(axial);
        ColorRectangle(canvas, new ShadingColor(shading), 150, 420, 126, 126);
        canvas.SetShadingFill(shading);
        canvas.Rectangle(300, 420, 126, 126);
        canvas.FillStroke();
      }
    }
        public void ProcessRequest(HttpContext context)
        {
            int ShowID = Convert.ToInt32(context.Request["showid"]);
            String userIDs = context.Request["ids"].ToString();
            String[] IDsList = userIDs.Split(',');

            Shows show = new Shows(ShowID);

            Document doc = new Document(PageSize.A4.Rotate(), 10, 10, -5, -5);
            Stream output = new MemoryStream();

            var writer = PdfWriter.GetInstance(doc, output);
            StyleSheet sheet = new StyleSheet();

            doc.Open();
            int pageCount = 0;
            foreach (String id in IDsList)
            {
                List<int> defaultUsers = new List<int>();

                int UserID = Convert.ToInt32(id);
                UserShows userShow = new UserShows(UserID, ShowID);
                printRingForUser(userShow, UserID, doc, ref defaultUsers, ref pageCount);

                List<int> tmp = null;
                foreach (int defid in defaultUsers)
                {
                    if (pageCount % 2 != 0)
                    {
                        doc.NewPage();
                    }
                    pageCount = 0;
                    printRingForUser(userShow, defid, doc, ref tmp, ref pageCount);
                }
                if (pageCount % 2 != 0)
                {
                    doc.NewPage();
                }
                pageCount = 0;

            }
            doc.Close();
            context.Response.ClearContent();
            context.Response.ContentType = "application/pdf";
            context.Response.AddHeader("content-disposition", String.Format("inline;filename=PreviewSchedule.pdf"));
            context.Response.BinaryWrite((output as MemoryStream).ToArray());
        }
Пример #44
0
 public string MergeMultiplePDFsToPDF(string[] fileList, string outMergeFile)
 {
     string returnStr = "";
     try
     {
         int f = 0;
         // we create a reader for a certain document
         PdfReader reader = new PdfReader(fileList[f]);
         // we retrieve the total number of pages
         int n = reader.NumberOfPages; //There are " + n + " pages in the original file.
         // step 1: creation of a document-object
         Document document = new Document(reader.GetPageSizeWithRotation(1));
         // step 2: we create a writer that listens to the document
         PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));
         // step 3: we open the document
         document.Open();
         PdfContentByte cb = writer.DirectContent;
         PdfImportedPage page;
         int rotation;
         // step 4: we add content
         while (f < fileList.Length)
         {
             int i = 0;
             while (i < n)
             {
                 i++;
                 document.SetPageSize(reader.GetPageSizeWithRotation(i));
                 document.NewPage();
                 page = writer.GetImportedPage(reader, i);
                 rotation = reader.GetPageRotation(i);
                 if (rotation == 90 || rotation == 270)
                 {
                     cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                 }
                 else
                 {
                     cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                 }
                 //Processed page i
             }
             f++;
             if (f < fileList.Length)
             {
                 reader = new PdfReader(fileList[f]);
                 // we retrieve the total number of pages
                 n = reader.NumberOfPages; //There are " + n + " pages in the original file.
             }
         }
         // step 5: we close the document
         document.Close();
         returnStr = "Succeed!";
     }
     catch (Exception e)
     {
         returnStr += e.Message + "<br />";
         returnStr += e.StackTrace;
     }
     return returnStr;
 }
    protected void DownloadPDF()
    {
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=UserDetails.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        StringWriter sw = new StringWriter();
        StringWriter sw2 = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        HtmlTextWriter hw2 = new HtmlTextWriter(sw2);
        Report.RenderControl(hw);

        // StringWriter sw2 = new StringWriter();
        // HtmlTextWriter hw2 = new HtmlTextWriter(sw2);
        // NonDisclosureAgreement.RenderControl(hw2);

        Document pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);
        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

        NonDisclosureAgreement.RenderControl(hw2);
        string myString = sw.ToString().Trim();

        //string myString3 = NonDisclosureAgreement.InnerHtml;
        string myString3 = sw2.ToString();
        //Header//
        //StringBuilder sb = new StringBuilder();

        //sb.Append(myString);
        //sb.Insert(0, '<div>  <p style='color: #800000; text-align:center'><strong>EXECUTIVE REPORT</strong></p><div><br/><br/>');
        //myString = sb.ToString();
        //Header//

        //////// AS EXAMPLE // ONLY REPLACE THE IMAGES FOR STATIC IMAGES LIKE COUNTRIES://////////////////
        ///  The next 4 lines made it work////
        // string myString2 = Server.MapPath("Advertiser/Ads/").ToString(CultureInfo.InvariantCulture);
        //string myString2 = Server.MapPath("Advertiser/images/").ToString(CultureInfo.InvariantCulture);
        //myString = myString.Replace("Advertiser/Ads/", myString2.ToString());
        //myString3 = myString.Replace("Advertiser/Ads/", myString3.ToString());

        //myString = Strings.Replace(myString, '<th', '<th align='center'');

        ///  The next 4 lines made it work////

        StringReader str = new StringReader(myString);
        StringReader str2 = new StringReader(myString3);
        pdfDoc.Open();

        htmlparser.Parse(str);

        // step 4: we create a table and add it to the document
           // BuyerTable2(pdfDoc);

        pdfDoc.NewPage();
        htmlparser.Parse(str2);

        pdfDoc.Close();
        Response.Write(pdfDoc);
        Response.End();
    }
Пример #46
0
        /// <summary>
        /// Merges multiple pdf files into 1 pdf file.
        /// </summary>
        /// <param name="FilesToMerge">Files to merger (Byte array for each file)</param>
        /// <returns>1 file with all the files passed in</returns>
        public static byte[] MergeFiles(IEnumerable<byte[]> FilesToMerge)
        {
            //Declare the memory stream to use
            using (var MemoryStreamToWritePdfWith = new MemoryStream())
            {
                //declare the new document which we will merge all the files into
                using (var NewFileToMergeIntoWith = new Document())
                {
                    //holds the byte array which we will return
                    byte[] ByteArrayToReturn;

                    //declare the pdf copy to write the data with
                    using (var PdfCopyWriter = new PdfCopy(NewFileToMergeIntoWith, MemoryStreamToWritePdfWith))
                    {
                        //set the page size of the new file
                        //NewFileToMergeIntoWith.SetPageSize(PageSize.GetRectangle("Letter").Rotate().Rotate());

                        //go open the new file that we are writing into
                        NewFileToMergeIntoWith.Open();

                        //now loop through all the files we want to merge
                        foreach (var FileToMerge in FilesToMerge)
                        {
                            //declare the pdf reader so we can copy it
                            using (var PdfFileReader = new PdfReader(FileToMerge))
                            {
                                //figure out how many pages are in this pdf, so we can add each of the pdf's
                                int PdfFilePageCount = PdfFileReader.NumberOfPages;

                                // loop over document pages (start with page 1...not a 0 based index)
                                for (int i = 1; i <= PdfFilePageCount; i++)
                                {
                                    //set the file size for this page
                                    NewFileToMergeIntoWith.SetPageSize(PdfFileReader.GetPageSize(i));

                                    //add a new page for the next page
                                    NewFileToMergeIntoWith.NewPage();

                                    //now import the page
                                    PdfCopyWriter.AddPage(PdfCopyWriter.GetImportedPage(PdfFileReader, i));
                                }
                            }
                        }

                        //now close the new file which we merged everyting into
                        NewFileToMergeIntoWith.Close();

                        //grab the buffer and throw it into a byte array to return
                        ByteArrayToReturn = MemoryStreamToWritePdfWith.GetBuffer();

                        //flush out the memory stream
                        MemoryStreamToWritePdfWith.Flush();
                    }

                    //now return the byte array
                    return ByteArrayToReturn;
                }
            }
        }
Пример #47
0
 // ===========================================================================
 public void Write(Stream stream)
 {
     string RESOURCE = Utility.ResourcePosters;
     // step 1
     using (Document document = new Document(PageSize.POSTCARD, 30, 30, 30, 30))
     {
         // step 2
         PdfWriter writer = PdfWriter.GetInstance(document, stream);
         // step 3
         document.Open();
         // step 4
         // Create and add a Paragraph
         Paragraph p = new Paragraph(
           "Foobar Film Festival",
           new Font(Font.FontFamily.HELVETICA, 22)
         );
         p.Alignment = Element.ALIGN_CENTER;
         document.Add(p);
         // Create and add an Image
         Image img = Image.GetInstance(Path.Combine(
           Utility.ResourceImage, "loa.jpg"
         ));
         img.SetAbsolutePosition(
           (PageSize.POSTCARD.Width - img.ScaledWidth) / 2,
           (PageSize.POSTCARD.Height - img.ScaledHeight) / 2
         );
         document.Add(img);
         // Now we go to the next page
         document.NewPage();
         document.Add(p);
         document.Add(img);
         // Add text on top of the image
         PdfContentByte over = writer.DirectContent;
         over.SaveState();
         float sinus = (float)Math.Sin(Math.PI / 60);
         float cosinus = (float)Math.Cos(Math.PI / 60);
         BaseFont bf = BaseFont.CreateFont();
         over.BeginText();
         over.SetTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_FILL_STROKE);
         over.SetLineWidth(1.5f);
         over.SetRGBColorStroke(0xFF, 0x00, 0x00);
         over.SetRGBColorFill(0xFF, 0xFF, 0xFF);
         over.SetFontAndSize(bf, 36);
         over.SetTextMatrix(cosinus, sinus, -sinus, cosinus, 50, 324);
         over.ShowText("SOLD OUT");
         over.EndText();
         over.RestoreState();
         // Add a rectangle under the image
         PdfContentByte under = writer.DirectContentUnder;
         under.SaveState();
         under.SetRGBColorFill(0xFF, 0xD7, 0x00);
         under.Rectangle(5, 5,
           PageSize.POSTCARD.Width - 10,
           PageSize.POSTCARD.Height - 10
         );
         under.Fill();
         under.RestoreState();
     }
 }
Пример #48
0
        // ===========================================================================
        public void Write(Stream stream)
        {
            var SQL =
      @"SELECT DISTINCT mc.country_id, c.country, count(*) AS c 
FROM film_country c, film_movie_country mc 
  WHERE c.id = mc.country_id
GROUP BY mc.country_id, country ORDER BY c DESC";
            // step 1
            using (Document document = new Document())
            {
                // step 2
                PdfWriter.GetInstance(document, stream);
                // step 3
                document.Open();
                // step 4
                using (var c = AdoDB.Provider.CreateConnection())
                {
                    c.ConnectionString = AdoDB.CS;
                    using (DbCommand cmd = c.CreateCommand())
                    {
                        cmd.CommandText = SQL;
                        c.Open();
                        using (var r = cmd.ExecuteReader())
                        {
                            while (r.Read())
                            {
                                Paragraph country = new Paragraph();
                                // the name of the country will be a destination
                                Anchor dest = new Anchor(
                                  r["country"].ToString(), FilmFonts.BOLD
                                );
                                dest.Name = r["country_id"].ToString();
                                country.Add(dest);
                                country.Add(string.Format(": {0} movies", r["c"].ToString()));
                                document.Add(country);
                                // loop over the movies
                                foreach (Movie movie in
                                    PojoFactory.GetMovies(r["country_id"].ToString()))
                                {
                                    // the movie title will be an external link
                                    Anchor imdb = new Anchor(movie.MovieTitle);
                                    imdb.Reference = string.Format(
                                      "http://www.imdb.com/title/tt{0}/", movie.Imdb
                                    );
                                    document.Add(imdb);
                                    document.Add(Chunk.NEWLINE);
                                }
                                document.NewPage();
                            }
                            // Create an internal link to the first page
                            Anchor toUS = new Anchor("Go back to the first page.");
                            toUS.Reference = "#US";
                            document.Add(toUS);
                        }
                    }
                }
            }
        }
Пример #49
0
// ---------------------------------------------------------------------------
    /**
     * Creates a PDF document.
     */
    public byte[] CreatePdf() {
      using (MemoryStream ms = new MemoryStream()) {
        // step 1
        using (Document document = new Document()) {
          // step 2
          PdfWriter.GetInstance(document, ms);
          // step 3
          document.Open();
          // step 4
          AddTif(document, RESOURCE1);
          document.NewPage();
          AddJBIG2(document, RESOURCE2);
          document.NewPage();
          AddGif(document, RESOURCE3);
        }
        return ms.ToArray();
      }
    }
Пример #50
0
        public static void MergeDocs()
        {
            //Step 1: Create a Docuement-Object
            iTextSharp.text.Document document = new iTextSharp.text.Document();
            try
            {
                //Step 2: we create a writer that listens to the document
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("D:\\Test1\\Final.pdf", FileMode.Create));
                //Step 3: Open the document
                document.Open();
                PdfContentByte cb = writer.DirectContent; PdfImportedPage page;
                int            n        = 0;
                int            rotation = 0;
                string[]       array2   = Directory.GetFiles("D:\\Test");
                for (int i = 0; i < array2.Length; i++)
                {
                    if (array2[i].Contains(".pdf"))
                    {
                        AddFile(array2[i]);
                    }
                }

                //Loops for each file that has been listed
                foreach (string filename in fileList)
                {
                    //The current file path
                    string filePath = sourcefolder + filename;
                    // we create a reader for the document
                    PdfReader reader = new PdfReader(filePath);
                    //Gets the number of pages to process
                    n = reader.NumberOfPages; int i = 0;
                    while (i < n)
                    {
                        i++; document.SetPageSize(reader.GetPageSizeWithRotation(1));
                        document.NewPage();
                        //Insert to Destination on the first page
                        if (i == 1)
                        {
                            Chunk fileRef = new Chunk(" ");
                            fileRef.SetLocalDestination(filename); document.Add(fileRef);
                        }
                        page     = writer.GetImportedPage(reader, i);
                        rotation = reader.GetPageRotation(i);
                        if (rotation == 90 || rotation == 270)
                        {
                            cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                        }
                        else
                        {
                            cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                        }
                    }
                }
            }
            catch (Exception e) { throw e; }
            finally { document.Close(); }
        }
Пример #51
0
        public void ResetPageNumbers(iTextSharp.text.Document document)
        {
            /* Check for double sided mode here */

            /* Page number represents the page number of the last page, not the potential new page that's coming. */

            if ((pageNumber % 2) == 0)
            {
                if (DoubleSidedMode)
                {
                    document.NewPage();
                    document.Add(new Chunk(""));
                }
            }

            document.NewPage();

            pageNumber = 0;
        }
Пример #52
0
        void WriteDocument(iTextSharp.text.Document doc, List <KeyValuePair <ISearchAlgorithm <string>, SearchReport <string> > > results, System.Drawing.Image initialGraph)
        {
            doc.AddCreationDate();
            doc.AddAuthor("GraphSEA");
            doc.AddCreator("GraphSEA");
            doc.AddHeader("Header", "GraphSEA - Graph search algorithms benchmark report");
            WriteHeader(doc);
            doc.NewPage();
            WriteGraph(doc, initialGraph, results[0].Value.Result.Start, results[0].Value.Result.End);
            doc.NewPage();
            WriteResultSummary(doc, results);
            doc.NewPage();
            // algorithms benchmarks
            foreach (var res in results)
            {
                CurrentReport = res.Value;
                WriteAlgorithmBenchmark(doc, res.Key, res.Value);
            }

            WriteTableOfContent(doc);
        }
Пример #53
0
        /// <summary>
        /// Saving the current report's content as a PDF file.
        /// </summary>
        /// <param name="doc">Retrieve it from xps.GetFixedDocumentSequence() or documentViewer.Document</param>
        /// <param name="fileNamePath"></param>
        /// <param name="pageSize">Example: PageSize.A4</param>
        /// <param name="quality">Resolution of the Images in the PDF </param>
        public static void Export(this FixedDocumentSequence doc, string fileNamePath, Rectangle pageSize, double quality = 1)
        {
            var paginator = doc.DocumentPaginator;

            var pageCount = paginator.PageCount;

            if (pageCount == 0)
            {
                return;
            }

            //create a new pdf doc with the specified size
            var pdfDoc = new iTextSharp.text.Document(pageSize);

            PdfWriter.GetInstance(pdfDoc, new FileStream(fileNamePath, FileMode.Create));
            pdfDoc.Open();

            //render pages to images and then save theme as a pdf file.
            for (var i = 0; i < pageCount; i++)
            {
                var visual = paginator.GetPage(i).Visual;

                var fe = visual as FrameworkElement;
                if (fe == null)
                {
                    continue;
                }

                var bmp = fe.RenderBitmap(quality);
                //var bmp = new RenderTargetBitmap((int)fe.ActualWidth, (int)fe.ActualHeight, dpiX, dpiY, PixelFormats.Default);
                bmp.Render(fe);

                var png = new PngBitmapEncoder();
                png.Frames.Add(BitmapFrame.Create(bmp));

                using (var ms = new MemoryStream())
                {
                    png.Save(ms);
                    //get image byte from stream
                    var imgBytes = ms.ToArray();
                    var pngImg   = Image.GetInstance(imgBytes);
                    //fit to page
                    pngImg.ScaleAbsolute(pdfDoc.PageSize.Width, pdfDoc.PageSize.Height);
                    pngImg.SetAbsolutePosition(0, 0);
                    //add to page
                    pdfDoc.Add(pngImg);
                    //start a new page
                    pdfDoc.NewPage();
                }
            }

            pdfDoc.Close();
        }
Пример #54
0
        public override void SaveDocument()
        {
            base.SaveDocument();
            PdfWriter wri = PdfWriter.GetInstance(pdf, File.Create(Path.Combine(OutputFolder, FileName + ".pdf")));

            pdf.Open();

            if (!string.IsNullOrEmpty(lnParameters.urlCover))
            {
                AddCover();
            }

            foreach (PdfChapter pdfChapter in pdfChapters)
            {
                pdf.NewPage();
                wri.PageEvent = null;
                wri.PageEvent = new PdfFooterEvent(pdfChapter.Title.Content);
                pdf.Add(pdfChapter);
            }

            pdf.Close();
            pdf.Dispose();
        }
Пример #55
0
        /// <summary>
        /// Devuelve el reporte del resguardo de equipo de computo de un área en particular o de
        /// toda la Coordinación
        /// </summary>
        public void ReportePorAreas()
        {
            myDocument = new iTextSharp.text.Document(PageSize.A4, 50, 50, 50, 50);
            string documento = Path.GetTempFileName() + ".pdf";

            try
            {
                if (idAreaReporte != 0)
                {
                    servidores = ((from n in servidores
                                   where n.IdArea == idAreaReporte
                                   select n).ToList()).ToObservableCollection();
                }

                PdfWriter writer = PdfWriter.GetInstance(myDocument, new FileStream(documento, FileMode.Create));

                myDocument.Open();

                foreach (ServidoresPublicos usuario in servidores)
                {
                    if (usuario.Mobiliario.Count > 0)
                    {
                        myDocument.NewPage();

                        myDocument = RElementosComunes.SetPageHeader(myDocument);

                        myDocument = RElementosComunes.SetSpaces(myDocument, 1);

                        myDocument = RElementosComunes.SetUserInfo(myDocument, usuario);

                        //myDocument = RElementosComunes.SetSpaces(myDocument, 1);

                        this.SetEquiposInfo(usuario.Mobiliario);

                        myDocument = RElementosComunes.SetSpaces(myDocument, 2);

                        myDocument = RElementosComunes.SetPageFooter(myDocument, usuario);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error ({0}) : {1}" + ex.Source + ex.Message, "Error Interno");
            }
            finally
            {
                myDocument.Close();
                System.Diagnostics.Process.Start(documento);
            }
        }
Пример #56
0
        public static List <byte[]> Split(PdfReader reader)
        {
            int p = 0;

            Document document;

            var data = new List <byte[]>();


            for (p = 1; p <= reader.NumberOfPages; p++)
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    document = new iTextSharp.text.Document();
                    PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
                    writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_2);
                    writer.CompressionLevel = PdfStream.BEST_COMPRESSION;
                    writer.SetFullCompression();
                    document.SetPageSize(reader.GetPageSize(p));
                    document.NewPage();
                    document.Open();
                    document.AddDocListener(writer);
                    PdfContentByte  cb         = writer.DirectContent;
                    PdfImportedPage pageImport = writer.GetImportedPage(reader, p);
                    int             rot        = reader.GetPageRotation(p);
                    if (rot == 90 || rot == 270)
                    {
                        cb.AddTemplate(pageImport, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(p).Height);
                    }
                    else
                    {
                        cb.AddTemplate(pageImport, 1.0F, 0, 0, 1.0F, 0, 0);
                    }
                    document.Close();
                    document.Dispose();
                    //File.WriteAllBytes(DestinationFolder + "/" + p + ".pdf", memoryStream.ToArray());

                    data.Add(memoryStream.ToArray());

                    if (OnSplitProcess != null)
                    {
                        OnSplitProcess(p, null);
                    }
                }
            }
            reader.Close();
            reader.Dispose();

            return(data);
        }
Пример #57
0
        private void img2pdf(List <string> ImageName)
        {
            string[] files = ImageName.ToArray();
            iTextSharp.text.Document document = new iTextSharp.text.Document(new iTextSharp.text.Rectangle(100f, 100f, 800f, 500f, 0));
            try
            {
                iTextSharp.text.pdf.PdfWriter.GetInstance(document, new FileStream(FileName, FileMode.Create, FileAccess.ReadWrite));
                document.Open();
                iTextSharp.text.Image image;
                for (int i = 0; i < files.Length; i++)
                {
                    if (String.IsNullOrEmpty(files[i]))
                    {
                        break;
                    }
                    image = iTextSharp.text.Image.GetInstance(files[i]);
                    if (image.Height > iTextSharp.text.PageSize.A4.Height - 25)
                    {
                        image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25);
                    }
                    else if (image.Width > iTextSharp.text.PageSize.A4.Width - 25)
                    {
                        image.ScaleToFit(iTextSharp.text.PageSize.A4.Width - 25, iTextSharp.text.PageSize.A4.Height - 25);
                    }
                    image.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE;
                    document.NewPage();
                    document.Add(image);
                    //iTextSharp.text.Chunk c1 = new iTextSharp.text.Chunk("Hello World");

                    //iTextSharp.text.Phrase p1 = new iTextSharp.text.Phrase();

                    //p1.Leading = 150;      //行间距

                    //document.Add(p1);
                }

                Console.WriteLine("转换成功!");
            }

            catch (Exception ex)

            {
                Console.WriteLine("转换失败,原因:" + ex.Message);
            }

            document.Close();
            PromptBox.Prompt("导出完成!");
            Console.ReadKey();
        }
        public string AddText(string PathSource, string PathTarget, int x, int y, int selectedPage, String text, int angle, int red, int green, int blue, int fontSize, float opacity)
        {
            try
            {
                iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(PathSource);
                int n = reader.NumberOfPages;

                if (!(selectedPage > 0 && selectedPage <= n))
                {
                    return(String.Format("Invalid Page {0}, the PDF has {1} pages", selectedPage, n));
                }

                iTextSharp.text.Document      document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1));
                iTextSharp.text.pdf.PdfWriter writer   = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(PathTarget, System.IO.FileMode.Create));

                document.Open();
                iTextSharp.text.pdf.PdfContentByte  cb = writer.DirectContent;
                iTextSharp.text.pdf.PdfImportedPage page;
                int rotation;
                int i = 0;
                // step 4: we add content
                while (i < n)
                {
                    i++;
                    document.NewPage();
                    page     = writer.GetImportedPage(reader, i);
                    rotation = reader.GetPageRotation(i);
                    if (rotation == 90 || rotation == 270)
                    {
                        cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                    }
                    else
                    {
                        cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                    }

                    if (i == selectedPage)
                    {
                        InsertText(cb, fontSize, x, y, text, angle, red, green, blue, opacity);
                    }
                }
                document.Close();
                return("");
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
Пример #59
0
        public override void OnCloseDocument(PdfWriter writer, iTextSharp.text.Document document)
        {
            base.OnCloseDocument(writer, document);

            /* Check page numbers to see if the number is even - You always want the pages to be even, so if it isn't, add a new blank page */
            if ((pageNumber % 2) == 0)
            {
                if (DoubleSidedMode)
                {
                    document.NewPage();
                    document.Add(new Phrase(""));
                }
            }
            pageNumber = 0;
        }
        public string SetSize(string sourceFile, string pSize, string targetPath)
        {
            try
            {
                string file = GetFullPath(sourceFile);
                iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(file);
                int n = reader.NumberOfPages;

                Rectangle pageSize = PageSize.GetRectangle(pSize);

                iTextSharp.text.Document      document = new iTextSharp.text.Document(pageSize);
                iTextSharp.text.pdf.PdfWriter writer   = iTextSharp.text.pdf.PdfWriter.GetInstance(document, new System.IO.FileStream(GetFullPath(targetPath), System.IO.FileMode.Create));
                document.Open();
                iTextSharp.text.pdf.PdfContentByte  cb = writer.DirectContent;
                iTextSharp.text.pdf.PdfImportedPage page;
                int rotation;
                int i = 0;

                reader = new iTextSharp.text.pdf.PdfReader(file);
                n      = reader.NumberOfPages;
                while (i < n)
                {
                    i++;
                    document.SetPageSize(pageSize);
                    document.NewPage();
                    page     = writer.GetImportedPage(reader, i);
                    rotation = reader.GetPageRotation(i);
                    if (rotation == 90)
                    {
                        cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                    }
                    else if ((rotation == 270))
                    {
                        cb.AddTemplate(page, 0f, 1f, -1f, 0f, reader.GetPageSizeWithRotation(i).Width, 0f);
                    }
                    else
                    {
                        cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                    }
                }
                document.Close();
                return("");
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }