GetPageSize() public method

public GetPageSize ( PdfDictionary page ) : Rectangle
page PdfDictionary
return iTextSharp.text.Rectangle
示例#1
1
        public static void SignPdfCert(String SRC, String DEST, String Reason, String Location, String certPassword, String certFile, String llx, String lly, String urx, String ury, int fontSize)
        {
            Pkcs12Store p12ks = new Pkcs12Store();
            FileStream fs = new FileStream(certFile, FileMode.Open);
            p12ks.Load(fs, certPassword.ToCharArray());
            String alias = "";
            foreach (String al in p12ks.Aliases)
            {
                if (p12ks.IsKeyEntry(al) && p12ks.GetKey(al).Key.IsPrivate)
                {
                    alias = al;
                    break;
                }
            }
            AsymmetricKeyParameter pk = p12ks.GetKey(alias).Key;
            ICollection<X509Certificate> chain = new List<X509Certificate>();
            foreach (X509CertificateEntry entry in p12ks.GetCertificateChain(alias))
            {
                chain.Add(entry.Certificate);
            }

            fs.Close();
            //Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser();
            //Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(cert.RawData) };

            IExternalSignature externalSignature = new PrivateKeySignature(pk, DigestAlgorithms.SHA512);
            PdfReader pdfReader = new PdfReader(SRC);
            FileStream signedPdf = new FileStream(DEST, FileMode.Create);  //the output pdf file
            Program.logLine("page size" + pdfReader.GetPageSize(1));

            PdfStamper pdfStamper = PdfStamper.CreateSignature(pdfReader, signedPdf, '\0');
            PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;
            //here set signatureAppearance at your will
            signatureAppearance.Reason = Reason;
            signatureAppearance.Location = Location;
            BaseFont bf = BaseFont.CreateFont();
            signatureAppearance.Layer2Font = new Font(bf, fontSize);
            signatureAppearance.SetVisibleSignature(new Rectangle(float.Parse(llx), float.Parse(lly), float.Parse(urx), float.Parse(ury)), 1, "sig");
            //signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;
            MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CMS);
            //MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0, CryptoStandard.CADES);
        }
 // ---------------------------------------------------------------------------
 /**
  * Inspect a PDF file and write the info to a txt file
  * @param writer StringBuilder
  * @param pdf PDF file bytes
  * @param fileName PDF filename
  */
 public static void Inspect(StringBuilder sb, byte[] pdf, string fileName)
 {
     PdfReader reader = new PdfReader(pdf);
     sb.Append(fileName);
     sb.Append(Environment.NewLine);
     sb.Append("Number of pages: ");
     sb.Append(reader.NumberOfPages);
     sb.Append(Environment.NewLine);
     Rectangle mediabox = reader.GetPageSize(1);
     sb.Append("Size of page 1: [");
     sb.Append(mediabox.Left);
     sb.Append(',');
     sb.Append(mediabox.Bottom);
     sb.Append(',');
     sb.Append(mediabox.Right);
     sb.Append(',');
     sb.Append(mediabox.Top);
     sb.Append("]");
     sb.Append(Environment.NewLine);
     sb.Append("Rotation of page 1: ");
     sb.Append(reader.GetPageRotation(1));
     sb.Append(Environment.NewLine);
     sb.Append("Page size with rotation of page 1: ");
     sb.Append(reader.GetPageSizeWithRotation(1));
     sb.Append(Environment.NewLine);
     sb.Append("Is rebuilt? ");
     sb.Append(reader.IsRebuilt().ToString());
     sb.Append(Environment.NewLine);
     sb.Append("Is encrypted? ");
     sb.Append(reader.IsEncrypted().ToString());
     sb.Append(Environment.NewLine);
     sb.Append(Environment.NewLine);
 }
示例#3
0
 public static float HeightOfFirstPage(byte[] pdfDocument)
 {
     using (var pdfReader = new PdfReader(pdfDocument))
     {
         return pdfReader.GetPageSize(1).Height;
     }
 }
示例#4
0
        static void GetPDFInfo(string pdf_filename)
        {
            PdfReader reader = new PdfReader(pdf_filename);
            Console.WriteLine("Tamaño de página en unidades Postscript...");

            float n = reader.NumberOfPages;

            for (int i = 1; i <= reader.NumberOfPages; i++)
            {
                Rectangle psize = reader.GetPageSize(i);
                float width = psize.Width;
                float height = psize.Height;
                string strPageRotation = null;

                if (height >= width)
                {
                    strPageRotation = "Vertical";
                }
                else
                {
                    strPageRotation = "Horizontal";
                }

                Console.WriteLine("Tamaño y rotación de la página {0} de {1}, {2} × {3}, {4}", i, reader.NumberOfPages, width, height, strPageRotation);
            }

            Console.WriteLine("Total de páginas PDF que contiene el documento, {0}", n);

        }
        public void Go()
        {
            PdfReader reader = new PdfReader(GetMasterDocument(38));
            Rectangle pageSize = reader.GetPageSize(1);
            using (FileStream stream = new FileStream(
                outputFile,
                FileMode.Create,
                FileAccess.Write))
            {
                using (Document document = new Document(pageSize, 0, 0, 0, 0))
                {
                    PdfWriter writer = PdfWriter.GetInstance(document, stream);
                    document.Open();
                    PdfPTable table = new PdfPTable(2);
                    table.TotalWidth = pageSize.Width;
                    table.LockedWidth = true;
                    table.DefaultCell.Border = Rectangle.NO_BORDER;
                    table.DefaultCell.FixedHeight = pageSize.Height / 2;
 
                    for (int i = 1; i <= reader.NumberOfPages; i++)
                    {
                        PdfImportedPage page = writer.GetImportedPage(reader, i);
                        table.AddCell(Image.GetInstance(page));
                    }
                    document.Add(table);
                }
            }
        }
 /// <summary>
 /// Fills out and flattens a form with the name, company and country.
 /// </summary>
 /// <param name="src"> the path to the original form </param>
 /// <param name="dest"> the path to the filled out form </param>
 public void ManipulatePdf(String src, String dest)
 {
     PdfReader reader = new PdfReader(src);
     PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create)); // create?
     int n = reader.NumberOfPages;
     Rectangle pagesize;
     for (int i = 1; i <= n; i++)
     {
         PdfContentByte under = stamper.GetUnderContent(i);
         pagesize = reader.GetPageSize(i);
         float x = (pagesize.Left + pagesize.Right)/2;
         float y = (pagesize.Bottom + pagesize.Top)/2;
         PdfGState gs = new PdfGState();
         gs.FillOpacity = 0.3f;
         under.SaveState();
         under.SetGState(gs);
         under.SetRGBColorFill(200, 200, 0);
         ColumnText.ShowTextAligned(under, Element.ALIGN_CENTER,
             new Phrase("Watermark", new Font(Font.FontFamily.HELVETICA, 120)),
             x, y, 45);
         under.RestoreState();
     }
     stamper.Close();
     reader.Close();
 }
示例#7
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;
                }
            }
        }
 /// <summary>
 /// Parses a page of a PDF file resulting in a list of
 /// TextItem and ImageItem objects.
 /// </summary>
 /// <param name="reader">a PdfReader</param>
 /// <param name="page">the page number of the page that needs to be parsed</param>
 /// <param name="header_height">header_height the height of the top margin</param>
 /// <returns>a list of TextItem and ImageItem objects</returns>
 public List<MyItem> GetContentItems(PdfReader reader, int page, float header_height)
 {
     PdfReaderContentParser parser = new PdfReaderContentParser(reader);
     Rectangle pageSize = reader.GetPageSize(page);
     MyRenderListener myRenderListener = new MyRenderListener(pageSize.Top - header_height);
     parser.ProcessContent(page, myRenderListener);
     return myRenderListener.Items;
 }
示例#9
0
        public static void PDFStamp(string inputPath, string outputPath, string watermarkPath)
        {
            try
            {
                PdfReader pdfReader = new PdfReader(inputPath);
                int numberOfPages = pdfReader.NumberOfPages;
                FileStream outputStream = new FileStream(outputPath, FileMode.Create);

                PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream);
                PdfContentByte waterMarkContent;

                iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);

                float width = psize.Width;

                float height = psize.Height;

                string watermarkimagepath = watermarkPath;
                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(watermarkimagepath);
                image.ScalePercent(70f);
                image.SetAbsolutePosition(width / 10, height / 9);

                /*                        image.ScaleAbsoluteHeight(10);
                                        image.ScaleAbsoluteW idth(10);*/

                //   waterMarkContent = pdfStamper.GetUnderContent(1);
                // waterMarkContent.AddImage(image);

                for (int i = 1; i <= numberOfPages; i++)
                {
                    //waterMarkContent = pdfStamper.GetUnderContent(i);//内容下层加水印
                    waterMarkContent = pdfStamper.GetOverContent(i);//内容上层加水印

                    waterMarkContent.AddImage(image);
                }

                pdfStamper.Close();
                pdfReader.Close();
                System.IO.File.Move(outputPath, inputPath);
            }
            catch (Exception)
            {

            }
              /*  finally
            {

                pdfStamper.Close();
                pdfReader.Close();
            }*/

            /*            System.IO.File.Delete(inputPath);

                        System.IO.File.Move(outputPath, inputPath);
                         System.IO.File.Delete(outputPath);*/
        }
        virtual public void TestRegion()
        {
            byte[] pdf = CreatePdfWithCornerText();

            PdfReader reader = new PdfReader(pdf);
            float pageHeight = reader.GetPageSize(1).Height;
            Rectangle upperLeft = new Rectangle(0, (int)pageHeight - 30, 250, (int)pageHeight);

            Assert.IsTrue(TextIsInRectangle(reader, "Upper Left", upperLeft));
            Assert.IsFalse(TextIsInRectangle(reader, "Upper Right", upperLeft));
        }
示例#11
0
文件: PdfFile.cs 项目: baluubas/Magic
        private PdfPage CreatePage(int pageIndex, PdfReader reader)
        {
            Rectangle pageSize = reader.GetPageSize(pageIndex);

            return new PdfPage(
                _container,
                _container.GetInstance<IPdfRasterizer>(),
                this,
                pageIndex,
                pageSize.Width,
                pageSize.Height);
        }
示例#12
0
        public string ParsePdf(string filePath)
        {
            string text = string.Empty;

            PdfReader reader = new iTextSharp.text.pdf.PdfReader(filePath);

            byte[] streamBytes = reader.GetPageContent(1);

            FileStream fStream = File.OpenRead(filePath);

            byte[] contents = new byte[fStream.Length];

            fStream.Read(contents, 0, (int)fStream.Length);

            fStream.Close();

            string s     = Encoding.UTF8.GetString(contents, 0, contents.Length);
            var    table = (Encoding.Default.GetString(streamBytes, 0, streamBytes.Length - 1)).Split(new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);

            byte[]      buf        = Encoding.Convert(Encoding.GetEncoding("iso-8859-1"), Encoding.UTF8, streamBytes);
            string      tempString = Encoding.UTF8.GetString(buf, 0, buf.Count());
            PRTokeniser tokenizer  = new PRTokeniser(streamBytes);

            while (tokenizer.NextToken())
            {
                if (tokenizer.TokenType == PRTokeniser.TK_STRING)
                {
                    text += tokenizer.StringValue;
                }
            }

            // create a reader (constructor overloaded for path to local file or URL)
            //PdfReader reader
            //    = new PdfReader("http://www.chinehamchat.com/Chineham_Chat_Advertisements.pdf");
            // total number of pages
            int n = reader.NumberOfPages;
            // size of the first page
            Rectangle psize = reader.GetPageSize(1);
            //float width = psize.Width;
            //float height = psize.Height;
            //Console.WriteLine("Size of page 1 of {0} => {1} × {2}", n, width, height);
            // file properties
            Hashtable   infoHash = reader.Info;
            ICollection keys     = infoHash.Keys;

            // Dictionary<string, string> infodict = (Dictionary<string,string>)reader.Info;
            foreach (string key in keys)
            {
                text += key + " => " + infoHash[key];
            }
            // Console.WriteLine(key+ " => " + infoHash[key]);
            return(text);
        }
示例#13
0
        protected void btnPrint_Click(object sender, ImageClickEventArgs e)
        {
            Warning[] warnings;
            string[] streamids;
            string mimeType;
            string encoding;
            string extension;

            byte[] bytes = ReportViewer1.LocalReport.Render("PDF", null, out mimeType,
                           out encoding, out extension, out streamids, out warnings);

            FileStream fs = new FileStream(HttpContext.Current.Server.MapPath("output.pdf"),
            FileMode.Create);
            fs.Write(bytes, 0, bytes.Length);
            fs.Close();

            //Open existing PDF
            Document document = new Document(PageSize.LETTER);
            PdfReader reader = new PdfReader(HttpContext.Current.Server.MapPath("output.pdf"));
            //Getting a instance of new PDF writer
            PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(
               HttpContext.Current.Server.MapPath("Print.pdf"), FileMode.Create));
            document.Open();
            PdfContentByte cb = writer.DirectContent;

            int i = 0;
            int p = 0;
            int n = reader.NumberOfPages;
            Rectangle psize = reader.GetPageSize(1);

            float width = psize.Width;
            float height = psize.Height;

            //Add Page to new document
            while (i < n)
            {
                document.NewPage();
                p++;
                i++;

                PdfImportedPage page1 = writer.GetImportedPage(reader, i);
                cb.AddTemplate(page1, 0, 0);
            }

            //Attach javascript to the document
            PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer);
            writer.AddJavaScript(jAction);
            document.Close();

            //Attach pdf to the iframe
            frmPrint.Attributes["src"] = "Print.pdf";
        }
示例#14
0
 public void TrimPDFFile(Stream outputStream, Stream inputStream, PageLayout pageLayout)
 {
     using (var reader = new PdfReader(inputStream))
     {
         var inputPageSize = reader.GetPageSize(1);
         var inputPage = reader.GetPageN(1);
         inputPage.Put(PdfName.MEDIABOX, new PdfRectangle(PageLayoutA4.GetLabelRect(0)));
         using (var stamper = new PdfStamper(reader, outputStream))
         {
             stamper.Writer.CloseStream = false;
             stamper.MarkUsed(inputPage);
         }
     }
 }
示例#15
0
        public void ExtractPages(string inputFile, string outputFile,
            List<int> extractPages, System.Windows.Forms.ProgressBar progres)
        {
            if (inputFile == outputFile)
            {
                System.Windows.Forms.MessageBox.Show("Nie możesz użyć pliku wejściowego jako wyjściowego do zapisu.");
            }

            PdfReader inputPDF = new PdfReader(inputFile);

            Document doc = new Document();
            PdfReader reader = new PdfReader(inputFile);
            progres.Maximum = reader.NumberOfPages;

            using (MemoryStream memoryStream = new MemoryStream())
            {
                PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);
                doc.Open();
                doc.AddDocListener(writer);
                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    progres.Value = i;
                    if (extractPages.FindIndex(s => s == i) == -1) continue;
                    doc.SetPageSize(reader.GetPageSize(i));
                    doc.NewPage();
                    PdfContentByte cb = writer.DirectContent;
                    PdfImportedPage pageImport = writer.GetImportedPage(reader, i);
                    int rot = reader.GetPageRotation(i);
                    if (rot == 90 || rot == 270)
                    {
                        cb.AddTemplate(pageImport, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                    }
                    else
                    {
                        cb.AddTemplate(pageImport, 1.0F, 0, 0, 1.0F, 0, 0);
                    }
                }
                reader.Close();
                doc.Close();
                try
                {
                    File.WriteAllBytes(outputFile, memoryStream.ToArray());
                }
                catch
                {
                    throw new Exception("Błąd przy próbie zapisu do pliku. Upewnij się iż żaden inny proces obecnie go nie używa.");
                }
            }
        }
示例#16
0
// ---------------------------------------------------------------------------
    /**
     * Manipulates a PDF file src
     * @param src the original PDF
     * @param stationery the resulting PDF
     */
    public byte[] ManipulatePdf(byte[] src, byte[] stationery) {
      ColumnText ct = new ColumnText(null);
      string SQL = 
@"SELECT country, id FROM film_country 
ORDER BY country
";        
      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()) {
              ct.AddElement(new Paragraph(
                24, new Chunk(r["country"].ToString())
              ));
            }
          }
        }
      }
      // Create a reader for the original document and for the stationery
      PdfReader reader = new PdfReader(src);
      PdfReader rStationery = new PdfReader(stationery);
      using (MemoryStream ms = new MemoryStream()) {
        // Create a stamper
        using (PdfStamper stamper = new PdfStamper(reader, ms)) {
          // Create an imported page for the stationery
          PdfImportedPage page = stamper.GetImportedPage(rStationery, 1);
          int i = 0;
          // Add the content of the ColumnText object 
          while(true) {
          // Add a new page
            stamper.InsertPage(++i, reader.GetPageSize(1));
            // Add the stationary to the new page
            stamper.GetUnderContent(i).AddTemplate(page, 0, 0);
            // Add as much content of the column as possible
            ct.Canvas = stamper.GetOverContent(i);
            ct.SetSimpleColumn(36, 36, 559, 770);
            if (!ColumnText.HasMoreText(ct.Go()))
                break;
          }
        }
        return ms.ToArray();     
      }
    }    
示例#17
0
 public void ManipulatePdf(string src, string dest)
 {
     PdfReader reader = new PdfReader(src);
     // We assume that there's a single large picture on the first page
     PdfDictionary page = reader.GetPageN(1);
     PdfDictionary resources = page.GetAsDict(PdfName.RESOURCES);
     PdfDictionary xobjects = resources.GetAsDict(PdfName.XOBJECT);
     Dictionary<PdfName, PdfObject>.KeyCollection.Enumerator enumerator = xobjects.Keys.GetEnumerator();
     enumerator.MoveNext();
     PdfName imgName = enumerator.Current;
     Image img = Image.GetInstance((PRIndirectReference) xobjects.GetAsIndirectObject(imgName));
     img.SetAbsolutePosition(0, 0);
     img.ScaleAbsolute(reader.GetPageSize(1));
     PdfStamper stamper = new PdfStamper(reader, new FileStream(dest,FileMode.Create));
     stamper.GetOverContent(1).AddImage(img);
     stamper.Close();
     reader.Close();
 }
示例#18
0
        public PdfRasterizer(string inputPdfPath, int pointsPerInch)
        {
            _pointsPerInch = pointsPerInch;
            // Extract info from pdf using iTextSharp
            try
            {
            using (Stream newpdfStream = new FileStream(inputPdfPath, FileMode.Open, FileAccess.Read))
            {
                using (PdfReader pdfReader = new PdfReader(newpdfStream))
                {
                    int numPagesToUse = pdfReader.NumberOfPages;
                    for (int pageNum = 1; pageNum <= numPagesToUse; pageNum++)
                    {
                        iTextSharp.text.Rectangle pageRect = pdfReader.GetPageSize(pageNum);
                        _pageSizes.Add(pageRect);
                        int pageRot = pdfReader.GetPageRotation(pageNum);
                        _pageRotationInfo.Add(pageRot);
                    }
                }
            }
            }
            catch (Exception excp)
            {
                logger.Error("Cannot open PDF with iTextSharp {0} excp {1}", inputPdfPath, excp.Message);
            }

            _lastInstalledVersion =
                GhostscriptVersionInfo.GetLastInstalledVersion(
                        GhostscriptLicense.GPL | GhostscriptLicense.AFPL,
                        GhostscriptLicense.GPL);

            try
            {
                _rasterizer.Open(inputPdfPath.Replace("/",@"\"), _lastInstalledVersion, false);
            }
            catch (Exception excp)
            {
                logger.Error("Cannot open PDF with ghostscript {0} excp {1}", inputPdfPath, excp.Message);
            }

            _inputPdfPath = inputPdfPath;
        }
示例#19
0
 public static void Test_ReadPdf_01(string file)
 {
     PdfReader reader = null;
     try
     {
         reader = new PdfReader(file);
         Trace.WriteLine("read pdf                          : \"{0}\"", file);
         Trace.WriteLine("number of pages                   : {0}", reader.NumberOfPages);
         Rectangle mediabox = reader.GetPageSize(1);
         Trace.WriteLine("size of page 1                    : [ {0}, {1}, {2}, {3} ]", mediabox.Left, mediabox.Bottom, mediabox.Right, mediabox.Top);
         Trace.WriteLine("rotation of page 1                : {0}", reader.GetPageRotation(1));
         Trace.WriteLine("page size with rotation of page 1 : {0}", reader.GetPageSizeWithRotation(1));
         Trace.WriteLine("file length                       : {0}", reader.FileLength);
         Trace.WriteLine("is rebuilt ?                      : {0}", reader.IsRebuilt());
         Trace.WriteLine("is encrypted ?                    : {0}", reader.IsEncrypted());
     }
     finally
     {
         if (reader != null)
             reader.Close();
     }
 }
示例#20
0
        public byte[] SetMetadati(System.IO.MemoryStream inputPdf, IDictionary <string, string> md)
        {
            inputPdf.Position = 0;
            iTextSharp.text.pdf.PdfReader prd   = new iTextSharp.text.pdf.PdfReader(inputPdf);
            iTextSharp.text.Rectangle     psize = prd.GetPageSize(1);
            Document doc = new Document(psize, 50, 50, 50, 70);

            System.IO.MemoryStream output = new System.IO.MemoryStream();
            output.Position = 0;

            iTextSharp.text.pdf.PdfWriter wr = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, output);
            doc.AddAuthor(md["author"]);
            doc.AddCreator(md["creator"]);
            doc.AddSubject(md["subject"]);
            wr.SetTagged();

            doc.Open();

            /*
             * EndPage pageEvent = new EndPage();
             * pageEvent.CIU = md["ciu"];
             * pageEvent.IDUfficio = md["id_ufficio"];
             * pageEvent.DocumentDate = md["data_emissione"];
             *
             * wr.PageEvent = pageEvent;
             */
            //wr.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);
            wr.SetPdfVersion(PdfWriter.PDF_VERSION_1_6);
            PdfContentByte content = wr.DirectContent;

            for (int i = 1; i <= prd.NumberOfPages; i++)
            {
                doc.NewPage();
                PdfImportedPage pg = wr.GetImportedPage(prd, i);
                content.AddTemplate(pg, 0, 0);
            }
            doc.Close();
            return(output.ToArray());
        }
        public void SplitDocumentTest()
        {
            MemoryStream readerStream = TestHelper.ReadTestFileToMemory();
             PdfReader reader = new PdfReader(readerStream);
             PdfSplit newDoc = new PdfSplit();
             newDoc.StartPage = 3;
             newDoc.EndPage = 4;
             Document pdf = new Document(reader.GetPageSize(3));
             newDoc.SetPdfDocument(pdf);

             MemoryStream writerStream = new MemoryStream();

             PdfWriter writer = PdfWriter.GetInstance(pdf, writerStream);
             newDoc.Writer = writer;
             Assert.AreEqual(0, writerStream.Length);

             newDoc.OpenPdfDocument();

             newDoc.SplitDocument(reader);

             Assert.IsTrue(writerStream.Length > 0);
             newDoc.ClosePdfDocument();
        }
示例#22
0
        /// <summary>Parses images from pdf document.</summary>
        /// <param name="filePath">The pdf-file full path.</param>
        /// <returns>Collection of images and streams that are associated with them.</returns>
        public static List<ParsedImage> ParseImages(string filePath)
        {
            var imgList = new List<ParsedImage>();
            var raf = new RandomAccessFileOrArray(filePath);
            var reader = new PdfReader(raf, null);

            try
            {
                for (var pageNumber = 1; pageNumber <= reader.NumberOfPages; pageNumber++)
                {
                    var pg = reader.GetPageN(pageNumber);
                    var size = reader.GetPageSize(pageNumber);
                    var res = (PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));

                    var xobj = (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
                    if (xobj == null)
                    {
                        continue;
                    }

                    foreach (var name in xobj.Keys)
                    {
                        var obj = xobj.Get(name);
                        if (!obj.IsIndirect())
                        {
                            continue;
                        }

                        var tg = (PdfDictionary)PdfReader.GetPdfObject(obj);

                        var type = (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));

                        if (!PdfName.IMAGE.Equals(type))
                        {
                            continue;
                        }

                        var refIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(CultureInfo.InvariantCulture));
                        var pdfObj = reader.GetPdfObject(refIndex);
                        var pdfStrem = (PdfStream)pdfObj;
                        var bytes = PdfReader.GetStreamBytesRaw((PRStream)pdfStrem);
                        if (bytes == null)
                        {
                            continue;
                        }

                        var memStream = new MemoryStream(bytes) { Position = 0 };
                        var img = Image.FromStream(memStream);
                        imgList.Add(new ParsedImage
                        {
                            Image = img,
                            ImageStream = memStream,
                            Format = img.RawFormat,
                            Width = size.Width,
                            Height = size.Height,
                            PerformedRotation = RotateFlipType.RotateNoneFlipNone
                        });
                    }
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }
            finally
            {
                reader.Close();
                raf.Close();
            }

            return imgList;
        }
        public ScanPages ExtractDocInfo(string uniqName, string fileName, int maxPagesToExtractFrom, ref int totalPages)
        {
            ScanPages scanPages = null;

            // Extract text and location from pdf pages
            using (Stream newpdfStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                List<List<LocationTextExtractionStrategyEx.TextInfo>> extractedTextAndLoc = new List<List<LocationTextExtractionStrategyEx.TextInfo>>();

                using (PdfReader pdfReader = new PdfReader(newpdfStream))
                {
                    int numPagesToUse = pdfReader.NumberOfPages;
                    if (numPagesToUse > maxPagesToExtractFrom)
                        numPagesToUse = maxPagesToExtractFrom;
                    int numPagesWithText = 0;
                    for (int pageNum = 1; pageNum <= numPagesToUse; pageNum++)
                    {
                        LocationTextExtractionStrategyEx locationStrategy = new LocationTextExtractionStrategyEx();
                        try
                        {
                            string text = PdfTextExtractor.GetTextFromPage(pdfReader, pageNum, locationStrategy);
                            if (text != "")
                                numPagesWithText++;
                            extractedTextAndLoc.Add(locationStrategy.TextLocationInfo);
                        }
                        catch (Exception excp)
                        {
                            logger.Error("Failed to extract from pdf {0}, page {1} excp {2}", fileName, pageNum, excp.Message);
                        }
                    }

                    // Create new structures for the information
                    int pageNumber = 1;
                    List<List<ScanTextElem>> scanPagesText = new List<List<ScanTextElem>>();
                    List<int> pageRotations = new List<int>();
                    foreach (List<LocationTextExtractionStrategyEx.TextInfo> pageInfo in extractedTextAndLoc)
                    {
                        iTextSharp.text.Rectangle pageRect = pdfReader.GetPageSize(pageNumber);
                        int pageRot = pdfReader.GetPageRotation(pageNumber);

                        // Check through found text to see if the page seems to be rotated
                        int[] rotCounts = new int[] { 0, 0, 0, 0 };
                        if (pageInfo.Count > 2)
                        {
                            foreach (LocationTextExtractionStrategyEx.TextInfo txtInfo in pageInfo)
                            {
                                int thisRotation = GetTextRotation(txtInfo.TopLeft, txtInfo.BottomRight);
                                rotCounts[(thisRotation / 90) % 4]++;
                            }
                        }
                        int maxRot = 0;
                        int maxRotCount = 0;
                        for (int i = 0; i < rotCounts.Length; i++)
                            if (maxRotCount < rotCounts[i])
                            {
                                maxRotCount = rotCounts[i];
                                maxRot = i * 90;
                            }
                        //Console.WriteLine("{2} Page{0}rot = {1}", pageNumber, maxRot, uniqName);

                        List<ScanTextElem> scanTextElems = new List<ScanTextElem>();
                        foreach (LocationTextExtractionStrategyEx.TextInfo txtInfo in pageInfo)
                        {
                            DocRectangle boundsRectPercent = ConvertToDocRect(txtInfo.TopLeft, txtInfo.BottomRight, pageRect, maxRot);
                            ScanTextElem sti = new ScanTextElem(txtInfo.Text, boundsRectPercent);
                            scanTextElems.Add(sti);
                        }
                        scanPagesText.Add(scanTextElems);
                        pageRotations.Add(maxRot);
                        pageNumber++;
                    }

                    // Total pages
                    totalPages = pdfReader.NumberOfPages;
                    scanPages = new ScanPages(uniqName, pageRotations, scanPagesText);
                    pdfReader.Close();

                    // Sleep for a little to allow other things to run
                    Thread.Sleep(100);
                }
            }

            // Return scanned text from pages
            return scanPages;
        }
示例#24
0
 /// <summary>
 /// 合併Pdf
 /// </summary>
 /// <param name="pdfList">文件路徑列表</param>
 /// <param name="FileName">合併后的文件路徑</param>
 public void MergePDF(List<string> pdfList, string FileName)
 {
     try
     {
         Document document_Merge = new Document(PageSize.A4);
         //創建實例
         PdfWriter writer = PdfWriter.GetInstance(document_Merge, new FileStream(FileName, FileMode.Create));
         document_Merge.Open();
         //設置title和頁眉
         writer.PageEvent = new HeaderAndFooterEvent();
         HeaderAndFooterEvent.header = "";
         HeaderAndFooterEvent.isPdfTable = false;
         HeaderAndFooterEvent.PAGE_NUMBER = false;
         HeaderAndFooterEvent.tpl = writer.DirectContent.CreateTemplate(100, 100);
         PdfReader reader;
         PdfContentByte cb = writer.DirectContent;
         PdfImportedPage newPage;
         for (int i = 0; i < pdfList.Count; i++)
         {
             reader = new PdfReader(pdfList[i]);
             iTextSharp.text.Rectangle psize = reader.GetPageSize(1);
             int iPageNum = reader.NumberOfPages;
             for (int j = 1; j <= iPageNum; j++)
             {
                 document_Merge.NewPage();
                 newPage = writer.GetImportedPage(reader, j);
                 cb.AddTemplate(newPage, 0, 0);
             }
         }
         document_Merge.Close();
     }
     catch (Exception ex)
     {
         throw new Exception("PdfManagement-->MergePDF-->" + ex.Message);
     }
 } 
示例#25
0
        public static void ResetMacrosDetails(string originalFile, string watermarked)
        {
            int page = 1;

              PdfReader reader = new PdfReader(originalFile);
              using (FileStream fs = new FileStream(watermarked, FileMode.Create, FileAccess.Write, FileShare.None))
              using (PdfStamper stamper = new PdfStamper(reader, fs))
              {
            PdfLayer layer = new PdfLayer("Text", stamper.Writer);

            Rectangle rect = reader.GetPageSize(page);
            PdfContentByte cb = stamper.GetOverContent(page);

            CMYKColor color = new CMYKColor(0f, 0f, 0f, 0f);
            cb.SetColorFill(color);
            cb.SetColorStroke(color);

            cb.BeginLayer(layer);

            double startHeight = rect.Height - 85;
            double height = 48;

            cb.MoveTo(0, startHeight);
            cb.LineTo(rect.Width, startHeight);
            cb.LineTo(rect.Width, startHeight - height);
            cb.LineTo(0, startHeight - height);
            cb.ClosePathFillStroke();

            startHeight = rect.Height - 143;
            double startWidth = rect.Width - 85;

            cb.MoveTo(startWidth, startHeight);
            cb.LineTo(rect.Width, startHeight);
            cb.LineTo(rect.Width, startHeight - height);
            cb.LineTo(startWidth, startHeight - height);
            cb.ClosePathFillStroke();

            startHeight = rect.Height - 150;
            double width = 65;
            height = 7;
            startWidth = 5;
            cb.MoveTo(startWidth, startHeight);
            cb.LineTo(startWidth + width, startHeight);
            cb.LineTo(startWidth + width, startHeight - height);
            cb.LineTo(startWidth, startHeight - height);
            cb.ClosePathFillStroke();

            startHeight = rect.Height - 179.5;
            height = 3;
            width = 4;
            startWidth = 115;

            for (int i = 0; i < 7; i++)
            {
              cb.MoveTo(startWidth, startHeight);
              cb.LineTo(startWidth + width, startHeight);
              cb.LineTo(startWidth + width, startHeight - height);
              cb.LineTo(startWidth, startHeight - height);
              cb.ClosePathFillStroke();

              startHeight = startHeight - 5.5;
            }

            startHeight = startHeight - 13;
            height = 2.7;

            for (int i = 0; i < 4; i++)
            {
              cb.MoveTo(startWidth, startHeight);
              cb.LineTo(startWidth + width, startHeight);
              cb.LineTo(startWidth + width, startHeight - height);
              cb.LineTo(startWidth, startHeight - height);
              cb.ClosePathFillStroke();

              startHeight = startHeight - 5.5;
            }

            cb.EndLayer();
              }
        }
示例#26
0
 public static void GetPdfSize(String pdfFile)
 {
     PdfReader pdfReader = new PdfReader(pdfFile);
     Program.logLine("page size" + pdfReader.GetPageSize(1));
     Console.WriteLine(pdfReader.GetPageSize(1).ToString().Substring(11, pdfReader.GetPageSize(1).ToString().IndexOf("(")-11));
 }
示例#27
0
        private Boolean lockPDF(String r_password, String w_password)
        {
            string rp = null, wp = null;

            ////////////////////////////////////////////////////
            // PDF施錠
            ////////////////////////////////////////////////////
            if (avaPDF)
            {
                // 一時ファイル取得
                String tmpFilePath = Path.GetTempFileName();

                // パスワードなしで読み込み可能かチェック
                try {
                    pdfReader = new PdfReader(dataGridView1.Rows[0].Cells[3].Value.ToString());
                } catch {
                    label2.Text = WindowsFormsApplication1.Properties.Resources.pdf1;
                    // "This document has been password-protected.";
                    return(false);
                }
                // オーナーパスワードが掛っているかチェック
                if (pdfReader.IsEncrypted())
                {
                    label2.Text = WindowsFormsApplication1.Properties.Resources.pdf2;
                    // "This document has been password-protected.";
                    return(false);
                }
                pdfDoc  = new iTextSharp.text.Document(pdfReader.GetPageSize(1));
                os      = new FileStream(tmpFilePath, FileMode.OpenOrCreate);
                pdfCopy = new PdfCopy(pdfDoc, os);
                // 出力ファイルにパスワード設定
                // rp:ユーザーパスワード
                // wp:オーナーパスワード(空の場合はユーザーパスワードと同じ値を設定)

                pdfCopy.Open();
                if (r_password.Length == 0)
                {
                    rp = null;
                }
                else
                {
                    rp = r_password;
                }
                if (w_password.Length == 0)
                {
                    wp = r_password;
                    pdfCopy.SetEncryption(
                        PdfCopy.STRENGTH128BITS, rp, wp,
                        PdfCopy.markAll);
                }
                else
                {
                    wp = w_password;
                    // AllowPrinting    印刷
                    // AllowCopy    内容のコピーと抽出
                    // AllowModifyContents  文書の変更
                    // AllowModifyAnnotations   注釈の入力
                    // AllowFillIn  フォーム・フィールドの入力と署名
                    // AllowScreenReaders   アクセシビリティのための内容抽出
                    // AllowAssembly    文書アセンブリ
                    pdfCopy.SetEncryption(
                        PdfCopy.STRENGTH128BITS, rp, wp,
                        PdfCopy.AllowScreenReaders | PdfCopy.AllowPrinting);
                }

                try {
                    // 出力ファイルDocumentを開く
                    pdfDoc.Open();
                    // アップロードPDFファイルの内容を出力ファイルに書き込む
                    pdfCopy.AddDocument(pdfReader);
                    // 出力ファイルDocumentを閉じる
                    pdfDoc.Close();
                    pdfCopy.Close();
                    os.Close();
                    pdfReader.Close();
                    // オリジナルファイルと一時ファイルを置き換える
                    File.Delete(dataGridView1.Rows[0].Cells[3].Value.ToString());
                    File.Move(tmpFilePath, dataGridView1.Rows[0].Cells[3].Value.ToString());
                } catch (Exception eX) {
                    label2.Text = WindowsFormsApplication1.Properties.Resources.error1 + eX.Message;
                    // "Saving failed." + eX.Message;
                    return(false);
                }
            }
            return(true);
        }
示例#28
0
        private Boolean unlockPDF(String r_password, String w_password)
        {
            Boolean NOPASS = true;

            ////////////////////////////////////////////////////
            // PDF解錠
            ////////////////////////////////////////////////////
            if (avaPDF)
            {
                // 一時ファイル取得
                String  tmpFilePath = Path.GetTempFileName();
                Boolean isRP        = false;
                Boolean isWP        = false;

                // パスワードなしで読み込めるかチェック
                try {
                    pdfReader = new PdfReader(dataGridView1.Rows[0].Cells[3].Value.ToString());
                    isRP      = false; // ユーザーパスワードなし
                                       // オーナーパスワードが掛っているかチェック
                    isWP   = (pdfReader.IsEncrypted()) ? true : false;
                    NOPASS = !(isRP || isWP);
                    pdfReader.Close();
                    pdfReader.Dispose();
                } catch {
                    isRP   = true;
                    NOPASS = false;
                }
                if (NOPASS)
                {
                    // パスワードがかかっていない
                    label2.Text = WindowsFormsApplication1.Properties.Resources.pdf2;
                    //"This document is not applied password.";
                    pdfReader.Close();
                    pdfReader.Dispose();
                    return(false);
                }
                if (isRP && (r_password.Length == 0))
                {
                    // ユーザーパスワードが掛っているが、入力されていない
                    label2.Text = WindowsFormsApplication1.Properties.Resources.pdf3;
                    // "This document has been user password-protected.";
                    return(false);
                }
                if (isWP && (w_password.Length == 0))
                {
                    // オーナーパスワードが掛っているが、入力されていない
                    label2.Text = WindowsFormsApplication1.Properties.Resources.pdf4;
                    //"This document has been owner password-protected.";
                    return(false);
                }

                String rp = (r_password.Length == 0) ? null : r_password;
                String wp = (w_password.Length == 0) ? r_password : w_password;

                try {
                    pdfReader = new PdfReader(dataGridView1.Rows[0].Cells[3].Value.ToString(), (byte[])System.Text.Encoding.ASCII.GetBytes(wp));
                } catch {
                    label2.Text = WindowsFormsApplication1.Properties.Resources.message2;
                    // "Password is incorrect.";
                    return(false);
                }


                try {
                    pdfDoc  = new iTextSharp.text.Document(pdfReader.GetPageSize(1));
                    os      = new FileStream(tmpFilePath, FileMode.OpenOrCreate);
                    pdfCopy = new PdfCopy(pdfDoc, os);
                    pdfCopy.Open();

                    pdfDoc.Open();
                    pdfCopy.AddDocument(pdfReader);

                    pdfDoc.Close();
                    pdfCopy.Close();
                    pdfReader.Close();
                    pdfReader.Dispose();
                    // オリジナルファイルと一時ファイルを置き換える
                    System.IO.File.Copy(tmpFilePath, dataGridView1.Rows[0].Cells[3].Value.ToString(), true);
                    System.IO.File.Delete(tmpFilePath);
                } catch (Exception eX) {
                    label2.Text = WindowsFormsApplication1.Properties.Resources.error1 + eX.Message;
                    // "Saving failed." + eX.Message;
                    return(false);
                }
            }
            return(true);
        }
示例#29
0
// ---------------------------------------------------------------------------     
    public void Write(Stream stream) {
      using (ZipFile zip = new ZipFile()) {
        // previous example
        Stationery s = new Stationery();
        byte[] stationary  = s.CreatePdf(s.CreateStationary());
        // reader for the src file
        PdfReader reader = new PdfReader(stationary);
        // initializations
        int pow = 1;
               
        do {
          Rectangle pageSize = reader.GetPageSize(1); 
          Rectangle newSize = (pow % 2) == 0 
            ? new Rectangle(pageSize.Width, pageSize.Height)
            : new Rectangle(pageSize.Height, pageSize.Width)
          ;
          Rectangle unitSize = new Rectangle(pageSize.Width, pageSize.Height);
          for (int i = 0; i < pow; i++) {
            unitSize = new Rectangle(unitSize.Height / 2, unitSize.Width);
          }
          int n = (int)Math.Pow(2, pow);
          int r = (int)Math.Pow(2, pow / 2);
          int c = n / r;           
          
          using (MemoryStream ms = new MemoryStream()) {
            // step 1
            using (Document document = new Document(newSize, 0, 0, 0, 0)) {
              // step 2
              PdfWriter writer = PdfWriter.GetInstance(document, ms);
              // step 3
              document.Open();
              // step 4
              PdfContentByte cb = writer.DirectContent;
              PdfImportedPage page;
              Rectangle currentSize;
              float offsetX, offsetY, factor;
              int total = reader.NumberOfPages;
              
              for (int i = 0; i < total; ) {
                if (i % n == 0) {
                  document.NewPage();
                }
                currentSize = reader.GetPageSize(++i);
                factor = Math.Min(
                    unitSize.Width / currentSize.Width,
                    unitSize.Height / currentSize.Height
                );
                offsetX = unitSize.Width * ((i % n) % c)
                  + (unitSize.Width - (currentSize.Width * factor)) / 2f
                ;
                offsetY = newSize.Height
                  - (unitSize.Height * (((i % n) / c) + 1))
                  + (unitSize.Height - (currentSize.Height * factor)) / 2f
                ;
                page = writer.GetImportedPage(reader, i);
                cb.AddTemplate(page, factor, 0, 0, factor, offsetX, offsetY);
              }
            }
            zip.AddEntry(string.Format(RESULT, n), ms.ToArray());
            ++pow;
          }
        } while (pow < 5); 
        zip.AddEntry(Utility.ResultFileName(s.ToString() + ".pdf"), stationary);
        zip.Save(stream);
      }
    }
示例#30
0
        public static void ResetBackgroundColor(string originalFile, string watermarked, string color)
        {
            int page = 1;

              PdfReader reader = new PdfReader(originalFile);
              using (FileStream fs = new FileStream(watermarked, FileMode.Create, FileAccess.Write, FileShare.None))
              using (PdfStamper stamper = new PdfStamper(reader, fs))
              {
            PdfLayer layer = new PdfLayer("BackgroundColor", stamper.Writer);

            Rectangle rect = reader.GetPageSize(page);
            PdfContentByte cb = stamper.GetOverContent(page);

            cb.BeginLayer(layer);

            // set color
            CMYKColor chosenColor;
            CMYKColor green = new CMYKColor(0.0809f, 0f, 0.1915f, 0.0784f); //TO DO: get green color

            // set template color
            if (color.Equals("yellow", StringComparison.OrdinalIgnoreCase))
            {
              chosenColor = new CMYKColor(0f, 0.2092f, 0.7741f, 0.0627f);
            }
            else if (color.Equals("red", StringComparison.OrdinalIgnoreCase))
            {
              chosenColor = new CMYKColor(0f, 0.7564f, 0.7372f, 0.3882f);
            }
            else if (color.Equals("purple", StringComparison.OrdinalIgnoreCase))
            {
              chosenColor = new CMYKColor(0.5118f, 0.6693f, 0f, 0.5020f);
            }
            else
            {
              chosenColor = new CMYKColor(0f, 0f, 0f, 0f);
            }

            cb.SetColorFill(chosenColor);
            cb.SetColorStroke(chosenColor);

            // draw name label
            double widthDiff = 23;
            double startHeight = rect.Height - 3;
            double midHeight = rect.Height - 18;
            double endHeight = rect.Height - 27;
            double startWidth = rect.Width * 1 / 3;
            double firstMidWidth = startWidth + widthDiff;
            double endWidth = rect.Width;
            double secondMidWidth = endWidth - widthDiff;

            cb.MoveTo(rect.Width * 1 / 3, startHeight);
            cb.LineTo(rect.Width, startHeight);
            cb.LineTo(rect.Width, midHeight);
            cb.CurveTo(secondMidWidth + (endWidth - secondMidWidth) / 1.4, endHeight + (midHeight - endHeight) / 4, secondMidWidth, endHeight);
            cb.LineTo(firstMidWidth, endHeight);
            cb.CurveTo(firstMidWidth - (firstMidWidth - startWidth) / 1.4, endHeight + (midHeight - endHeight) / 4, startWidth, midHeight);
            cb.ClosePathFillStroke();

            // reset flag
            cb.SetColorFill(green);
            cb.SetColorStroke(green);

            startHeight = endHeight - 0.5;
            double heightDiff = 8.5;
            widthDiff = 13;

            cb.MoveTo(endWidth - widthDiff, startHeight);
            cb.LineTo(endWidth, startHeight);
            cb.LineTo(endWidth, startHeight - heightDiff);
            cb.LineTo(endWidth - widthDiff, startHeight - heightDiff);
            cb.ClosePathFillStroke();

            startHeight = startHeight - heightDiff - 2;
            cb.MoveTo(endWidth - widthDiff, startHeight);
            cb.LineTo(endWidth, startHeight);
            cb.LineTo(endWidth, startHeight - heightDiff);
            cb.LineTo(endWidth - widthDiff, startHeight - heightDiff);
            cb.ClosePathFillStroke();

            startHeight = startHeight - heightDiff - 2;
            cb.MoveTo(endWidth - widthDiff, startHeight);
            cb.LineTo(endWidth, startHeight);
            cb.LineTo(endWidth, startHeight - heightDiff);
            cb.LineTo(endWidth - widthDiff, startHeight - heightDiff);
            cb.ClosePathFillStroke();

            double mealLabelStartHeight = rect.Height - 30;
            double mealLabelHeight = 8;
            double mealLabelStartWidth = rect.Width / 3;
            double mealLabelWidth = 120;

            cb.MoveTo(mealLabelStartWidth, mealLabelStartHeight);
            cb.LineTo(mealLabelStartWidth + mealLabelWidth, mealLabelStartHeight);
            cb.LineTo(mealLabelStartWidth + mealLabelWidth, mealLabelStartHeight - mealLabelHeight);
            cb.LineTo(mealLabelStartWidth, mealLabelStartHeight - mealLabelHeight);
            cb.ClosePathFillStroke();

            double macrosStartHeight = rect.Height - 55;
            double macrosStartWidth = rect.Width / 3 + 5;
            double macrosWidth = 20;
            double macrosHeight = 10;

            for (int i = 0; i < 4; i++)
            {
              cb.MoveTo(macrosStartWidth, macrosStartHeight);
              cb.LineTo(macrosStartWidth + macrosWidth, macrosStartHeight);
              cb.LineTo(macrosStartWidth + macrosWidth, macrosStartHeight - macrosHeight);
              cb.LineTo(macrosStartWidth, macrosStartHeight - macrosHeight);
              cb.ClosePathFillStroke();

              macrosStartWidth = macrosStartWidth + macrosWidth + 13;
            }

            // Close the layer
            cb.EndLayer();
              }
        }
示例#31
0
        private void readPdf(string fileToOpen)
        {
            try
            {

            PdfReader reader = new PdfReader(fileToOpen);
            // total number of pages
            int n = reader.NumberOfPages;
            // size of the first page
            Rectangle psize = reader.GetPageSize(1);
            float width = psize.Width;
            float height = psize.Height;
                string asd = "Size of page 1 of {0} => {1} × {2}"+ n+ width+ height;
             RoutesBoxList.Items.Add(asd);
            // file properties
            Dictionary<string, string> infodict = reader.Info;

            for (int page = 1; page <= reader.NumberOfPages; page++)
            {
                ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                string currentText = PdfTextExtractor.GetTextFromPage(reader, page, strategy);

                currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
                                RoutesBoxList.Items.Add(currentText);
                                TestBox.Text = currentText;
            }
            foreach (KeyValuePair<string, string> kvp in infodict)
                RoutesBoxList.Items.Add(kvp.Key + " => " + kvp.Value);
            }
            catch (Exception e)
            {
                RoutesBoxList.Items.Add("Cannot deserialize PDF " + fileToOpen);
            }
        }
示例#32
0
        public static void Watermark(string originalFile, string watermarked)
        {
            int page = 1;

              PdfReader reader = new PdfReader(originalFile);
              using (FileStream fs = new FileStream(watermarked, FileMode.Create, FileAccess.Write, FileShare.None))
              using (PdfStamper stamper = new PdfStamper(reader, fs))
              {
            PdfLayer layer = new PdfLayer("Text", stamper.Writer);

            Rectangle rect = reader.GetPageSize(page);
            PdfContentByte cb = stamper.GetOverContent(page);

            cb.EndLayer();
              }
        }
示例#33
0
 private static void ApplyWaterMark(string filePath)
 {
     Logger.LogI("ApplyWatermark -> " + filePath);
     var watermarkedFile = Path.GetFileNameWithoutExtension(filePath) + "-w.pdf";
     using (var reader1 = new PdfReader(filePath))
     {
         using (var fs = new FileStream(watermarkedFile, FileMode.Create, FileAccess.Write, FileShare.None))
         using (var stamper = new PdfStamper(reader1, fs))
         {
             var pageCount = reader1.NumberOfPages;
             var layer = new PdfLayer("WatermarkLayer", stamper.Writer);
             for (var i = 1; i <= pageCount; i++)
             {
                 var rect = reader1.GetPageSize(i);
                 var cb = stamper.GetUnderContent(i);
                 cb.BeginLayer(layer);
                 cb.SetFontAndSize(BaseFont.CreateFont(
                     BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 50);
                 var gState = new PdfGState {FillOpacity = 0.25f};
                 cb.SetGState(gState);
                 cb.SetColorFill(BaseColor.BLACK);
                 cb.BeginText();
                 cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER,
                     "(c)2015 ScrapEra", rect.Width/2, rect.Height/2, 45f);
                 cb.EndText();
                 cb.EndLayer();
             }
         }
     }
     File.Delete(filePath);
 }
示例#34
0
 /// <summary>
 ///  Copy pages from the given reader into the given content.
 /// </summary>
 /// <param name="content">The content container into which data will be copied</param>
 /// <param name="reader">
 ///  The reader to collect data from a PDF document that has been opened with full permissions
 /// </param>
 /// <returns>An await-able task that will complete when all pages are copied</returns>
 private async Task GetPages(PdfContentByte content, PdfReader reader)
 {
     int pageCount = reader.NumberOfPages;
     for (int currentPage = 1; currentPage <= pageCount; currentPage++)
     {
         document.SetPageSize(reader.GetPageSize(currentPage));
         document.NewPage();
         var page = await Task.Run<PdfImportedPage>(() =>
             writer.GetImportedPage(reader, currentPage));
         var rotation = reader.GetPageRotation(currentPage);
         if (rotation == 90 || rotation == 270)
         {
             // Add the page with a transform matrix that rotates 90 degrees.
             await Task.Run(() => content.AddTemplate(page, 0f, -1f, 1f, 0f, 0f, page.Height));
         }
         else
         {
             // Add the page with an identity transform.
             await Task.Run(() => content.AddTemplate(page, 1f, 0f, 0f, 1f, 0f, 0f));
         }
     }
 }