GetPageSizeWithRotation() public method

public GetPageSizeWithRotation ( PdfDictionary page ) : Rectangle
page PdfDictionary
return iTextSharp.text.Rectangle
示例#1
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();
        }
示例#2
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);
                }
            }
        }
示例#3
0
            void ApplyRotation(PdfDictionary pageN, ByteBuffer out_p)
            {
                if (!cstp.rotateContents)
                {
                    return;
                }
                Rectangle page     = reader.GetPageSizeWithRotation(pageN);
                int       rotation = page.Rotation;

                switch (rotation)
                {
                case 90:
                    out_p.Append(PdfContents.ROTATE90);
                    out_p.Append(page.Top);
                    out_p.Append(' ').Append('0').Append(PdfContents.ROTATEFINAL);
                    break;

                case 180:
                    out_p.Append(PdfContents.ROTATE180);
                    out_p.Append(page.Right);
                    out_p.Append(' ');
                    out_p.Append(page.Top);
                    out_p.Append(PdfContents.ROTATEFINAL);
                    break;

                case 270:
                    out_p.Append(PdfContents.ROTATE270);
                    out_p.Append('0').Append(' ');
                    out_p.Append(page.Right);
                    out_p.Append(PdfContents.ROTATEFINAL);
                    break;
                }
            }
示例#4
0
        public void AddFile(string fileName)
        {
            var reader = new PdfReader(fileName);

            for (var i = 1; i <= reader.NumberOfPages; i++)
            {
                var size = reader.GetPageSizeWithRotation(i);
                _document.SetPageSize(size);
                _document.NewPage();

                var page = _writer.GetImportedPage(reader, i);
                var rotation = reader.GetPageRotation(i);

                switch (rotation)
                {
                    case 90:
                        _writer.DirectContent.AddTemplate(page, 0, -1, 1, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                        break;
                    // TODO case 180
                    case 270:
                        _writer.DirectContent.AddTemplate(page, 0, 1, -1, 0, reader.GetPageSizeWithRotation(i).Width, 0);
                        break;
                    default:
                        _writer.DirectContent.AddTemplate(page, 0, 0);
                        break;
                }
            }

            reader.Close();
        }
示例#5
0
文件: Form9.cs 项目: Spritutu/ntxx
 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;
 }
示例#6
0
        void CreatePdf(string input_path, IList<int> pages, string output_path)
        {
            // open a reader for the source file
            PdfReader reader = new PdfReader(input_path);

            try
            {
                reader.RemoveUnusedObjects();

                // get output file
                using (var fs = new FileStream(output_path, FileMode.Create, FileAccess.Write))
                {
                    // create input document
                    var input_doc = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(pages[0]));
                    // create the writer
                    PdfWriter writer = PdfWriter.GetInstance(input_doc, fs);
                    try
                    {
                        writer.SetFullCompression();
                        input_doc.Open();
                        try
                        {
                            // for each page copy the page directly from the reader into the writer
                            PdfContentByte cb = writer.DirectContent;
                            foreach (int page_number in pages)
                            {
                                input_doc.SetPageSize(reader.GetPageSizeWithRotation(page_number));
                                input_doc.NewPage();

                                PdfImportedPage page = writer.GetImportedPage(reader, page_number);

                                int rotation = reader.GetPageRotation(page_number);
                                if (rotation == 90 || rotation == 270)
                                    cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(page_number).Height);
                                else
                                    cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                            }
                        }
                        finally
                        {
                            input_doc.Close();
                        }
                    }
                    finally
                    {
                        writer.Close();
                    }
                }
            }
            finally
            {
                reader.Close();
            }
        }
示例#7
0
        public static String Concatenate(String[] pdfs)
        {
            String temporaryFilePath = GetTemporaryFile();
            try
            {
                int pdfFileIndex = 0;
                PdfReader reader = new PdfReader(pdfs[pdfFileIndex]);
                int totalPages = reader.NumberOfPages;

                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(temporaryFilePath, FileMode.Create));
                // step 3: we open the document
                document.Open();

                PdfContentByte cb = writer.DirectContent;
                PdfImportedPage page;

                while (true)
                {
                    int i = 0;
                    while (i < totalPages)
                    {
                        i++;
                        document.SetPageSize(reader.GetPageSizeWithRotation(i));
                        document.NewPage();
                        page = writer.GetImportedPage(reader, i);

                        cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                    }
                    pdfFileIndex++;
                    if (pdfFileIndex < pdfs.Length)
                    {
                        reader = new PdfReader(pdfs[pdfFileIndex]);
                        // we retrieve the total number of pages
                        totalPages = reader.NumberOfPages;
                    }
                    else
                        break;
                }
                // step 5: we close the document
                document.Close();
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message);
                Console.Error.WriteLine(e.StackTrace);
            }

            return temporaryFilePath;
        }
        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);
            }
        }
 // ---------------------------------------------------------------------------
 /**
  * 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);
 }
示例#10
0
        public void ConvertToImage(string _rutaPDF, int width, int height)
        {
            iTextSharp.text.pdf.PdfReader reader = null;
            int currentPage = 1;
            int pageCount   = 0;

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            reader = new iTextSharp.text.pdf.PdfReader(_rutaPDF);
            reader.RemoveUnusedObjects();
            pageCount = reader.NumberOfPages;
            string ext = System.IO.Path.GetExtension(_rutaPDF);

            for (int i = 1; i <= 1; i++)
            {
                iTextSharp.text.pdf.PdfReader reader1 = new iTextSharp.text.pdf.PdfReader(_rutaPDF);
                string outfile = _rutaPDF.Replace((System.IO.Path.GetFileName(_rutaPDF)), (System.IO.Path.GetFileName(_rutaPDF).Replace(".pdf", "") + "_" + i.ToString()) + ext);
                reader1.RemoveUnusedObjects();
                iTextSharp.text.Document    doc    = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(currentPage));
                iTextSharp.text.pdf.PdfCopy pdfCpy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(outfile, System.IO.FileMode.Create));
                doc.Open();
                for (int j = 1; j <= 1; j++)
                {
                    iTextSharp.text.pdf.PdfImportedPage page = pdfCpy.GetImportedPage(reader1, currentPage);
                    pdfCpy.SetFullCompression();
                    pdfCpy.AddPage(page);
                    currentPage += 1;
                }
                doc.Close();
                pdfCpy.Close();
                reader1.Close();
                reader.Close();
            }
        }
示例#11
0
// ---------------------------------------------------------------------------
    /**
     * Manipulates a PDF file src with the file dest as result
     * @param src the original PDF
     */
    public override byte[] ManipulatePdf(byte[] src) {
      locations = PojoFactory.GetLocations();
      // Create a reader
      PdfReader reader = new PdfReader(src);
      using (MemoryStream ms = new MemoryStream()) {
        // Create a stamper
        using (PdfStamper stamper = new PdfStamper(reader, ms)) {
          // Loop over the days and screenings
          int page = 1;
          Rectangle rect;
          float top;
          PdfAnnotation annotation;
          Movie movie;
          foreach (string day in PojoFactory.GetDays()) {
            foreach (Screening screening in PojoFactory.GetScreenings(day)) {
              rect = GetPosition(screening);
              movie = screening.movie;
              // Annotation for press previews
              if (screening.Press) {
                annotation = PdfAnnotation.CreateStamp(
                  stamper.Writer, rect, "Press only", "NotForPublicRelease"
                );
                annotation.Color = BaseColor.BLACK;
                annotation.Flags = PdfAnnotation.FLAGS_PRINT;
              }
              // Annotation for screenings that are sold out
              else if (IsSoldOut(screening)) {
                top = reader.GetPageSizeWithRotation(page).Top;
                annotation = PdfAnnotation.CreateLine(
                    stamper.Writer, rect, "SOLD OUT",
                    top - rect.Top, rect.Right,
                    top - rect.Bottom, rect.Left
                );
                annotation.Title = movie.MovieTitle;
                annotation.Color = BaseColor.WHITE;
                annotation.Flags = PdfAnnotation.FLAGS_PRINT;
                annotation.BorderStyle = new PdfBorderDictionary(
                  5, PdfBorderDictionary.STYLE_SOLID
                );
              }
              // Annotation for screenings with tickets available
              else {
                annotation = PdfAnnotation.CreateSquareCircle(
                  stamper.Writer, rect, "Tickets available", true
                );
                annotation.Title = movie.MovieTitle;
                annotation.Color = BaseColor.BLUE;
                annotation.Flags = PdfAnnotation.FLAGS_PRINT;
                annotation.Border = new PdfBorderArray(
                  0, 0, 2, new PdfDashPattern()
                );
              }
              stamper.AddAnnotation(annotation, page);
            }
            page++;
          }
        }
        return ms.ToArray();
      }
    }    
示例#12
0
        static void MergePdfFiles(string foldernameInput, string folderNameOutput)
        {
            var files = Directory.GetFiles(foldernameInput, "*.pdf");
            int count = 0;

            foreach (var file in files)
            {
                var pdfReader = new iTextSharp.text.pdf.PdfReader(file);

                var pdfDoc = new iTextSharp.text.Document(pdfReader.GetPageSizeWithRotation(1));

                //            'Instantiate a PdfWriter that listens to the pdf document
                var outputfile = Path.Combine(folderNameOutput, Path.GetFileName(file));
                var writer     = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, new FileStream(outputfile, FileMode.Create));
                pdfDoc.Open();
                int pagenumber = 0;
                int pagecount  = pdfReader.NumberOfPages;
                var cb         = writer.DirectContent;
                while (pagenumber < pagecount)
                {
                    pdfDoc.NewPage();
                    var importedPage = writer.GetImportedPage(pdfReader, pagenumber + 1);
                    writer.DirectContentUnder.AddTemplate(importedPage, 0, 0);
                    if (pagenumber == 0)
                    {
                        CopyFormToText(pdfReader, cb);
                    }
                    pagenumber++;
                }
                writer.Flush();
                pdfDoc.Close();
                count++;
            }
        }
示例#13
0
        public void ExtractPage(string sourcePdfPath, string outputPdfPath,
            int pageNumber, string password = "")
        {
            PdfReader reader = null;
            Document document = null;
            PdfCopy pdfCopyProvider = null;
            PdfImportedPage importedPage = null;

            try
            {
                // Intialize a new PdfReader instance with the contents of the source Pdf file:
                reader = new PdfReader(sourcePdfPath, Encoding.UTF8.GetBytes(password));

                // Capture the correct size and orientation for the page:
                document = new Document(reader.GetPageSizeWithRotation(pageNumber));

                // Initialize an instance of the PdfCopyClass with the source
                // document and an output file stream:
                pdfCopyProvider = new PdfCopy(document,
                    new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));

                document.Open();

                // Extract the desired page number:
                importedPage = pdfCopyProvider.GetImportedPage(reader, pageNumber);
                pdfCopyProvider.AddPage(importedPage);
                document.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#14
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);
      }
    }
示例#15
0
        /// <summary>
        /// réorganise les pages d'un document pdf selon la liste d'indices de pages
        /// <param name="inputFile">fichier à ordonner</param>
        /// <param name="indexList">pages dans l'ordre voulu</param>
        /// </summary>
        public static void DoReorder(string inputFile, int[] indexList)
        {
            //var inputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");
            //var output = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Output.pdf");
            var output = Path.Combine(ServiceCfg.OutputFolderPath, Path.GetFileName(inputFile));

            //Bind a reader to our input file
            var reader = new PdfReader(inputFile);

            //Create our output file, nothing special here
            using (FileStream fs = new FileStream(output, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (Document doc = new Document(reader.GetPageSizeWithRotation(1)))
                {
                    //Use a PdfCopy to duplicate each page
                    using (PdfCopy copy = new PdfCopy(doc, fs))
                    {
                        doc.Open();
                        copy.SetLinearPageMode();
                        for (int i = 1; i <= reader.NumberOfPages; i++)
                        {
                            copy.AddPage(copy.GetImportedPage(reader, i));
                        }
                        //Reorder pages
                        copy.ReorderPages(indexList);
                        doc.Close();
                    }
                }
            }
        }
示例#16
0
        public static void MergeFiles(string destinationFile, string[] sourceFiles)
        {
            try
            {
                int f = 0;
                // we create a reader for a certain document
                PdfReader reader = new PdfReader(sourceFiles[f]);
                // we retrieve the total number of pages
                int n = reader.NumberOfPages;
                //Console.WriteLine("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(destinationFile, 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 < sourceFiles.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);
                        }
                        //Console.WriteLine("Processed page " + i);
                    }
                    f++;
                    if (f < sourceFiles.Length)
                    {
                        reader = new PdfReader(sourceFiles[f]);
                        // we retrieve the total number of pages
                        n = reader.NumberOfPages;
                        //Console.WriteLine("There are " + n + " pages in the original file.");
                    }
                }			// step 5: we close the document
                document.Close();
            }
            catch (Exception e)
            {
                string strOb = e.Message;
            }
        }
 // based on http://itextsharp.sourceforge.net/examples/Encrypt.cs
 public string ModifyPermissions(string PathSource, string PathTarget, string UserPassword, List <int> Permissons)
 {
     try
     {
         int PDFpermisson = 0;
         foreach (int permisson in Permissons)
         {
             PDFpermisson = PDFpermisson | permisson;
         }
         iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(PathSource);
         int n = reader.NumberOfPages;
         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));
         writer.SetEncryption(iTextSharp.text.pdf.PdfWriter.STRENGTH128BITS, UserPassword, null, (int)PDFpermisson);
         // step 3: we open the document
         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.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);
             }
         }
         document.Close();
         return("");
     }
     catch (Exception e)
     {
         return(e.Message);
     }
 }
示例#18
0
 /// <summary>
 /// Concatenates two or more PDF files into one file.
 /// </summary>
 /// <param name="inputFiles">A string array containing the names of the pdf files to concatenate</param>
 /// <param name="outputFile">Name of the concatenated file.</param>
 public void ConcatenatePDFFiles(String[] inputFiles, String outputFile)
 {
     if (inputFiles != null && inputFiles.Length > 0)
     {
         if (!String.IsNullOrEmpty(outputFile) && !String.IsNullOrWhiteSpace(outputFile))
         {
             var concatDocument = new iTextSharpText.Document();
             var outputCopy     = new iTextSharpPDF.PdfCopy(concatDocument, new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite));
             concatDocument.Open();
             try
             {
                 for (int loop = 0; loop <= inputFiles.GetUpperBound(0); loop++)
                 {
                     var inputDocument = new iTextSharpPDF.PdfReader(inputFiles[loop]);
                     for (int pageLoop = 1; pageLoop <= inputDocument.NumberOfPages; pageLoop++)
                     {
                         concatDocument.SetPageSize(inputDocument.GetPageSizeWithRotation(pageLoop));
                         outputCopy.AddPage(outputCopy.GetImportedPage(inputDocument, pageLoop));
                     }
                     inputDocument.Close();
                     outputCopy.FreeReader(inputDocument);
                     inputDocument = null;
                 }
                 concatDocument.Close();
                 outputCopy.Close();
             }
             catch
             {
                 if (concatDocument != null && concatDocument.IsOpen())
                 {
                     concatDocument.Close();
                 }
                 if (outputCopy != null)
                 {
                     outputCopy.Close();
                 }
                 if (File.Exists(outputFile))
                 {
                     try
                     {
                         File.Delete(outputFile);
                     }
                     catch { }
                 }
                 throw;
             }
         }
         else
         {
             throw new ArgumentNullException("outputFile", exceptionArgumentNullOrEmptyString);
         }
     }
     else
     {
         throw new ArgumentNullException("inputFiles", exceptionArgumentNullOrEmptyString);
     }
 }
 public static void MergeFiles(string destinationFile, List<string> files, bool removeMergedFiles)
 {
     try
     {
         var f = 0;
         var reader = new PdfReader(files.First());
         var numberOfPages = reader.NumberOfPages;
         var document = new Document(reader.GetPageSizeWithRotation(1));
         var writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
         document.Open();
         var content = writer.DirectContent;
         while (f < files.Count)
         {
             var i = 0;
             while (i < numberOfPages)
             {
                 i++;
                 document.SetPageSize(reader.GetPageSizeWithRotation(i));
                 document.NewPage();
                 var page = writer.GetImportedPage(reader, i);
                 var 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);
             }
             f++;
             if (f < files.Count)
             {
                 reader = new PdfReader(files[f]);
                 numberOfPages = reader.NumberOfPages;
             }
         }
         document.Close();
         if (removeMergedFiles)
         {
             DeleteMergedFiles(files);
         }
     }
     catch (Exception e)
     {
         var strOb = e.Message;
     }
 }
        public static void FileImposition(float width, float height,
            Stream exitStream, int numberDocOfPages, bool rotateSeconds, params Stream[] fileStreams)
        {
            Point currentPoint = null;
            var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

            //http://forums.asp.net/t/1692347.aspx/1
            using (var document = new Document(new Rectangle(width, height)))
            {
                var writer = PdfWriter.GetInstance(document, exitStream);
                {
                    document.Open();
                    var content = writer.DirectContent;
                    document.NewPage();
                    var fileCount = 1;
                    foreach (var fileStream in fileStreams)
                    {
                        var reader = new PdfReader(fileStream);
                        var numberOfPages = reader.NumberOfPages;
                        var isSecond = (fileCount % 2 == 0);
                        if (numberOfPages > 0)
                        {
                            var page = writer.GetImportedPage(reader, 1);
                            var pageRect = reader.GetPageSizeWithRotation(1);
                            var matrix = new Matrix();
                            if (currentPoint == null)
                            {
                                currentPoint = new Point(0, pageRect.Height);
                            }
                            matrix.Translate(currentPoint.X, currentPoint.Y);
                            matrix.Rotate(-90);

                            currentPoint.Y += pageRect.Height;

                            content.AddTemplate(page, matrix);
                            content.BeginText();
                            content.SetFontAndSize(baseFont, 100);
                            content.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Data", currentPoint.X, currentPoint.Y,0);
                            content.EndText();
                            currentPoint.Y += 100;

                        }

                        fileCount++;
                    }

                }
            }
        }
        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);
            }
        }
示例#22
0
        private void StartThread()
        {
            List <String> filePaths = new List <string>();

            // create one-page pdfs first
            iTextSharp.text.pdf.PdfReader reader = null;
            int    currentPage = 1;
            int    pageCount   = 0;
            String filepath    = textBox_file.Text;

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            reader = new iTextSharp.text.pdf.PdfReader(filepath);
            reader.RemoveUnusedObjects();
            pageCount = reader.NumberOfPages;
            string ext = System.IO.Path.GetExtension(filepath);

            for (int i = 1; i <= pageCount; i++)
            {
                iTextSharp.text.pdf.PdfReader reader1 = new iTextSharp.text.pdf.PdfReader(filepath);
                string outfile = filepath.Replace((System.IO.Path.GetFileName(filepath)), (System.IO.Path.GetFileName(filepath).Replace(".pdf", "") + "_" + i.ToString()) + ext);
                reader1.RemoveUnusedObjects();
                iTextSharp.text.Document    doc    = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(currentPage));
                iTextSharp.text.pdf.PdfCopy pdfCpy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(outfile, System.IO.FileMode.Create));
                doc.Open();
                for (int j = 1; j <= 1; j++)
                {
                    iTextSharp.text.pdf.PdfImportedPage page = pdfCpy.GetImportedPage(reader1, currentPage);
                    pdfCpy.AddPage(page);
                    currentPage += 1;
                }
                doc.Close();
                pdfCpy.Close();
                reader1.Close();
                reader.Close();

                filePaths.Add(outfile);
            }

            DecomposeData decompose = new DecomposeData
            {
                filePathsPdf = filePaths,
                folder       = textBox_destFolder.Text
            };

            backgroundWorker1.RunWorkerAsync(decompose);

            label_status.Text      = localization.GetValueForItem(LocalizedItem.TextSearchStarted).Replace("%i", filePaths.Count.ToString());
            label_status.ForeColor = Color.Blue;
        }
示例#23
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.");
                }
            }
        }
示例#24
0
        /// <summary>
        /// Splits the PDF file
        /// </summary>
        /// <param name="filepath">The file to split</param>
        private void Split(string filepath)
        {
            this.statut.Text = "Début de la division";
            this.statut.Refresh();
            this.document.Text = Path.GetFileName(filepath);
            this.document.Refresh();
            PdfReader reader      = null;
            int       currentPage = 1;
            int       pageCount   = 0;
            string    dirPath     = Path.GetDirectoryName(filepath);

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            reader = new iTextSharp.text.pdf.PdfReader(filepath);
            reader.RemoveUnusedObjects();
            pageCount = reader.NumberOfPages;
            string ext = System.IO.Path.GetExtension(filepath);

            for (int i = 1; i <= pageCount; i++)
            {
                this.statut.Text = "En cours de division " + i + " / " + pageCount;
                this.statut.Refresh();
                iTextSharp.text.pdf.PdfReader reader1 = new iTextSharp.text.pdf.PdfReader(filepath);
                string outfile = filepath.Replace(System.IO.Path.GetFileName(filepath), (System.IO.Path.GetFileName(filepath).Replace(FileExtension.PDF, string.Empty) + "_" + i.ToString()) + ext);
                outfile = outfile.Substring(0, dirPath.Length).Insert(dirPath.Length, string.Empty) + "\\" + Path.GetFileName(filepath).Replace(FileExtension.PDF, string.Empty) + "_" + i.ToString() + ext;
                reader1.RemoveUnusedObjects();
                iTextSharp.text.Document    doc    = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(currentPage));
                iTextSharp.text.pdf.PdfCopy pdfCpy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(outfile, System.IO.FileMode.OpenOrCreate));
                doc.Open();
                for (int j = 1; j <= 1; j++)
                {
                    iTextSharp.text.pdf.PdfImportedPage page = pdfCpy.GetImportedPage(reader1, currentPage);
                    pdfCpy.AddPage(page);
                    currentPage += 1;
                }

                this.progressBar1.PerformStep();
                this.progressPages = this.progressPages + 1;
                this.label1.Text   = this.progressPages + " / " + this.nbpages;
                this.label1.Refresh();
                this.statut.Text = "Fin de la division " + i + " / " + pageCount;
                this.statut.Refresh();
                doc.Close();
                pdfCpy.Close();
                reader1.Close();
                reader.Close();
            }
        }
示例#25
0
        }     //  end setGraphTitle

        private void AddWatermarkText(string sourceFile, string outputFile, string watermarkText, float watermarkFontSize, float watermarkFontOpacity, float watermarkRotation)
        {
            iTextSharp.text.pdf.PdfReader      reader       = null;
            iTextSharp.text.pdf.PdfStamper     stamper      = null;
            iTextSharp.text.pdf.PdfGState      gstate       = null;
            iTextSharp.text.pdf.PdfContentByte underContent = null;
            iTextSharp.text.Rectangle          rect         = null;

            int pageCount = 0;

            try
            {
                reader  = new iTextSharp.text.pdf.PdfReader(sourceFile);
                rect    = reader.GetPageSizeWithRotation(1);
                stamper = new PdfStamper(reader, new System.IO.FileStream(outputFile, System.IO.FileMode.CreateNew), '\0', true);

                iTextSharp.text.pdf.BaseFont watermarkFont = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.COURIER,
                                                                                                     iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED);
                gstate               = new iTextSharp.text.pdf.PdfGState();
                gstate.FillOpacity   = watermarkFontOpacity;
                gstate.StrokeOpacity = watermarkFontOpacity;
                pageCount            = reader.NumberOfPages;
                for (int i = 1; i <= pageCount; i++)
                {
                    underContent = stamper.GetUnderContent(i);
                    underContent.SaveState();
                    underContent.SetGState(gstate);
                    underContent.SetColorFill(iTextSharp.text.BaseColor.DARK_GRAY);
                    underContent.BeginText();
                    underContent.SetFontAndSize(watermarkFont, watermarkFontSize);
                    underContent.SetTextMatrix(30, 30);
                    underContent.ShowTextAligned(iTextSharp.text.Element.ALIGN_CENTER, watermarkText, rect.Width / 2, rect.Height / 2, watermarkRotation);
                    underContent.EndText();
                    underContent.RestoreState();
                }   //  end for i loop

                stamper.Close();
                reader.Close();
            }   //  end try
            catch (Exception ex)
            {
                throw ex;
            } //  end
            return;
        }     //  end AddWatermark
示例#26
0
        public static Stream JoinPdfs(bool InsertBlankPages, List<Stream> Pdfs)
        {
            if (Pdfs.Count == 0)
                throw new System.ArgumentNullException(nameof(Pdfs));

            // Only One PDF - Possible Reference Bug v's Memory/Speed (Returning Param Memory Stream)
            if (Pdfs.Count == 1)
                return Pdfs[0];

            // Join Pdfs
            var msBuilder = new MemoryStream();

            var pdfLastPageSize = PageSize.A4;
            var pdfDoc = new Document();
            var pdfCopy = new PdfSmartCopy(pdfDoc, msBuilder);
            pdfDoc.Open();
            pdfCopy.CloseStream = false;

            for (int i = 0; i < Pdfs.Count; i++)
            {
                var pdf = Pdfs[i];
                var pdfReader = new PdfReader(pdf);

                if (InsertBlankPages && (pdfCopy.CurrentPageNumber % 2) == 0)
                {
                    pdfCopy.AddPage(pdfLastPageSize, 0);
                }

                for (int indexPage = 1; indexPage <= pdfReader.NumberOfPages; indexPage++)
                {
                    pdfLastPageSize = pdfReader.GetPageSizeWithRotation(indexPage);
                    var page = pdfCopy.GetImportedPage(pdfReader, indexPage);
                    pdfDoc.SetPageSize(pdfLastPageSize);
                    pdfCopy.AddPage(page);
                }

                pdfReader.Close();
            }

            pdfDoc.Close();
            pdfCopy.Close();
            msBuilder.Position = 0;

            return msBuilder;
        }
示例#27
0
        public static void BreakApart()
        {
            var reader = new iTextSharp.text.pdf.PdfReader(@"C:\Projects\31g\trunk\temp\20140208110036.pdf");

            for (var i = 1; i < reader.NumberOfPages; i++)
            {
                var document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(i));

                var pdfCopyProvider = new iTextSharp.text.pdf.PdfCopy(document,
                                                                      new System.IO.FileStream(string.Format(@"C:\Projects\31g\trunk\temp\pdf\20140208110036_{0}.pdf", i), System.IO.FileMode.Create));
                document.Open();
                var importedPage = pdfCopyProvider.GetImportedPage(reader, i);
                pdfCopyProvider.AddPage(importedPage);
                document.Close();
            }

            reader.Close();
        }
        /// <summary> iTextSharp_PNG 无法正常进行展出操作
        ///
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="outputPath"></param>
        /// <returns></returns>
        List <PPTPage> SplitePDF(string filepath, string outputPath)
        {
            List <PPTPage> pages = new List <PPTPage>();

            iTextSharp.text.pdf.PdfReader reader = null;
            int currentPage = 1;
            int pageCount   = 0;

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            reader = new iTextSharp.text.pdf.PdfReader(filepath);
            reader.RemoveUnusedObjects();
            pageCount = reader.NumberOfPages;

            for (int i = 1; i <= pageCount;)
            {
                string outfile = System.IO.Path.Combine(outputPath, i + ".png");
                iTextSharp.text.Document    doc    = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(currentPage));
                iTextSharp.text.pdf.PdfCopy pdfCpy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(outfile, System.IO.FileMode.Create));
                doc.Open();
                for (int j = 1; j <= 1; j++)
                {
                    iTextSharp.text.pdf.PdfImportedPage page = pdfCpy.GetImportedPage(reader, currentPage);
                    pdfCpy.SetFullCompression();
                    pdfCpy.AddPage(page);
                    currentPage += 1;
                }

                Console.WriteLine("PDF TO IMAGES - {0}/{1}", ++i, pageCount);
                pages.Add(new PPTPage()
                {
                    Cover = outfile
                });

                pdfCpy.Flush();
                doc.Close();
                pdfCpy.Close();
                reader.Close();
            }

            return(pages);
        }
示例#29
0
        public void ExtractPages(string sourcePdfPath, 
            string outputPdfPath, int[] extractThesePages)
        {
            PdfReader reader = null;
            Document sourceDocument = null;
            PdfCopy pdfCopyProvider = null;
            PdfImportedPage importedPage = null;

            try
            {
                // Intialize a new PdfReader instance with the
                // contents of the source Pdf file:
                reader = new PdfReader(sourcePdfPath);

                // For simplicity, I am assuming all the pages share the same size
                // and rotation as the first page:
                sourceDocument = new Document(reader.GetPageSizeWithRotation(extractThesePages[0]));

                // Initialize an instance of the PdfCopyClass with the source
                // document and an output file stream:
                pdfCopyProvider = new PdfCopy(sourceDocument,
                    new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));

                sourceDocument.Open();

                // Walk the array and add the page copies to the output file:
                foreach (int pageNumber in extractThesePages)
                {
                    importedPage = pdfCopyProvider.GetImportedPage(reader, pageNumber);
                    pdfCopyProvider.AddPage(importedPage);
                }
                sourceDocument.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#30
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();
     }
 }
示例#31
0
        public void ExtractPages(string sourcePdfPath, string outputPdfPath,
    int startPage, int endPage, string password = "")
        {
            PdfReader reader = null;
            Document sourceDocument = null;
            PdfCopy pdfCopyProvider = null;
            PdfImportedPage importedPage = null;

            try
            {

                // Intialize a new PdfReader instance with the contents of the source Pdf file:
                reader = new PdfReader(sourcePdfPath, Encoding.UTF8.GetBytes(password));

                // For simplicity, I am assuming all the pages share the same size
                // and rotation as the first page:
                sourceDocument = new Document(reader.GetPageSizeWithRotation(startPage));

                // Initialize an instance of the PdfCopyClass with the source
                // document and an output file stream:
                pdfCopyProvider = new PdfCopy(sourceDocument,
                    new System.IO.FileStream(outputPdfPath, System.IO.FileMode.Create));

                sourceDocument.Open();

                // Walk the specified range and add the page copies to the output file:
                for (int i = startPage; i <= endPage; i++)
                {
                    importedPage = pdfCopyProvider.GetImportedPage(reader, i);
                    pdfCopyProvider.AddPage(importedPage);
                }
                sourceDocument.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#32
0
        /// <summary>
        /// Create a PDF from a subset of source PDF pages specified in a page range.
        /// </summary>
        /// <param name="FirstPage">first source page</param>
        /// <param name="LastPage">last source page</param>
        /// <param name="srcPath">the source file</param>
        /// <param name="outputPath">New PDF with the specefied pages.</param>
        /// <returns>True if all goes well</returns>
        public static bool RipPdf(int FirstPage, int LastPage, string srcPath, string outputPath)
        {
            bool result = true;

            PdfReader reader = null;
            Document document = null;
            PdfCopy pdfCopyProvider = null;
            PdfImportedPage importedPage = null;

            // Intialize a new PdfReader instance with the contents of the source Pdf file:
            using (reader = new PdfReader(srcPath))
            {

                // For simplicity, I am assuming all the pages share the same size
                // and rotation as the first page:
                using (document = new Document(reader.GetPageSizeWithRotation(FirstPage)))
                {

                    // Initialize an instance of the PdfCopyClass with the source
                    // document and an output file stream:
                    pdfCopyProvider = new PdfCopy(document,
                        new System.IO.FileStream(outputPath, System.IO.FileMode.Create));

                    document.Open();

                    // Walk the specified range and add the page copies to the output file:
                    for (int i = FirstPage; i <= LastPage; i++)
                    {
                        importedPage = pdfCopyProvider.GetImportedPage(reader, i);
                        pdfCopyProvider.AddPage(importedPage);
                    }

                }//Dispose of document
            }//Dispose of reader

            return result;
        }
示例#33
0
        public static void SplitePDF(string filepath)
        {
            iTextSharp.text.pdf.PdfReader reader = null;
            int currentPage = 1;
            int pageCount   = 0;

            //string filepath_New = filepath + "\\PDFDestination\\";

            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            //byte[] arrayofPassword = encoding.GetBytes(ExistingFilePassword);
            reader = new iTextSharp.text.pdf.PdfReader(filepath);
            reader.RemoveUnusedObjects();
            pageCount = reader.NumberOfPages;
            string ext = System.IO.Path.GetExtension(filepath);

            for (int i = 1; i <= pageCount; i++)
            {
                iTextSharp.text.pdf.PdfReader reader1 = new iTextSharp.text.pdf.PdfReader(filepath);
                string outfile = filepath.Replace((System.IO.Path.GetFileName(filepath)), (System.IO.Path.GetFileName(filepath).Replace(".pdf", "") + "_" + i.ToString()) + ext);
                reader1.RemoveUnusedObjects();
                iTextSharp.text.Document    doc    = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(currentPage));
                iTextSharp.text.pdf.PdfCopy pdfCpy = new iTextSharp.text.pdf.PdfCopy(doc, new System.IO.FileStream(outfile, System.IO.FileMode.Create));
                pdfCpy.SetFullCompression();
                doc.Open();
                for (int j = 1; j <= 1; j++)
                {
                    iTextSharp.text.pdf.PdfImportedPage page = pdfCpy.GetImportedPage(reader1, currentPage);
                    pdfCpy.AddPage(page);
                    currentPage += 1;
                }
                doc.Close();
                pdfCpy.Close();
                reader1.Close();
                reader.Close();
            }
        }
示例#34
0
        private void printPreview(List <string> prInfo)
        {
            string newPath     = Directory.GetCurrentDirectory().Replace("bin\\Debug", "PersonalRecords\\");
            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            Array.ForEach(Directory.GetFiles(@"" + newPath + "\\AthleteNameAdded\\"), File.Delete);
            string fileNameTemplate = @"" + newPath + "Template.pdf";

            string[] meetInfo      = getMeetInfo();
            int      textSpacing   = 7;
            int      textAlignment = PdfContentByte.ALIGN_CENTER;

            string[] prInfoArray = prInfo.ToArray();
            for (int i = 0; i < prInfoArray.Length - 1; i++)
            {
                if (i % 8 == 0)
                {
                    int    fileCount_Ath        = Directory.GetFiles(newPath + "\\AthleteNameAdded", "*", SearchOption.TopDirectoryOnly).Length;
                    string fileNameAthleteAdded = @"" + newPath + "\\AthleteNameAdded\\testAthleteAddedCopy" + fileCount_Ath + ".pdf";

                    using (var reader = new iTextSharp.text.pdf.PdfReader(@"" + fileNameTemplate))
                        using (var fileStream = new FileStream(@"" + fileNameAthleteAdded, FileMode.Create, FileAccess.Write))
                        {
                            var document = new Document(reader.GetPageSizeWithRotation(1));
                            var writer   = PdfWriter.GetInstance(document, fileStream);

                            document.Open();

                            document.NewPage();

                            var baseFont     = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                            var importedPage = writer.GetImportedPage(reader, 1);

                            var contentByte = writer.DirectContent;
                            contentByte.BeginText();
                            contentByte.SetFontAndSize(baseFont, 12);
                            string meetDate = meetInfo[1].Split(' ')[0];

                            //text to be added---The /NAME/
                            var athleteName = prInfoArray[i] + " " + prInfoArray[i + 1];
                            //adds in the name
                            int x = 225;
                            foreach (var line in athleteName)
                            {
                                contentByte.ShowTextAligned(textAlignment, line.ToString(), x, 593, 0);
                                x = x + textSpacing;
                            }

                            var trackEvent = prInfoArray[i + 2];

                            //adds in the event
                            int x2 = 157;
                            foreach (var line in trackEvent)
                            {
                                contentByte.ShowTextAligned(textAlignment, line.ToString(), x2, 537, 0);
                                x2 = x2 + textSpacing;
                            }

                            //adds in the time/distance
                            contentByte.ShowTextAligned(textAlignment, formatMark(prInfoArray, i, 3), x2 + 30, 537, 0);

                            //adds in the meet name
                            int x5 = 157;
                            foreach (var line in meetInfo[0])
                            {
                                contentByte.ShowTextAligned(textAlignment, line.ToString(), x5, 510, 0);
                                x5 = x5 + textSpacing;
                            }

                            //adds in the meet date
                            int x6 = 240;
                            foreach (var line in meetDate)
                            {
                                contentByte.ShowTextAligned(textAlignment, line.ToString(), x6, 483, 0);
                                x6 = x6 + textSpacing;
                            }


                            //-----------------------second pr-----------------------------------------------------
                            try
                            {
                                var athleteName2 = prInfoArray[i + 4] + " " + prInfoArray[i + 5];
                                //adds in the athlete name
                                int x3 = 225;
                                foreach (var line in athleteName2)
                                {
                                    contentByte.ShowTextAligned(textAlignment, line.ToString(), x3, 205, 0);
                                    x3 = x3 + textSpacing;
                                }

                                var trackEvent2 = prInfoArray[i + 6];
                                //adds in the event
                                int x4 = 157;
                                foreach (var line in trackEvent2)
                                {
                                    contentByte.ShowTextAligned(textAlignment, line.ToString(), x4, 149, 0);
                                    x4 = x4 + textSpacing;
                                }

                                //adds in the time/distance
                                contentByte.ShowTextAligned(textAlignment, formatMark(prInfoArray, i, 7), x4 + 30, 149, 0);

                                //adds in the meet name
                                int x7 = 157;
                                foreach (var line in meetInfo[0])
                                {
                                    contentByte.ShowTextAligned(textAlignment, line.ToString(), x7, 122, 0);
                                    x7 = x7 + textSpacing;
                                }

                                //adds in the meet date
                                int x8 = 240;
                                foreach (var line in meetDate)
                                {
                                    contentByte.ShowTextAligned(textAlignment, line.ToString(), x8, 95, 0);
                                    x8 = x8 + textSpacing;
                                }

                                contentByte.EndText();
                                contentByte.AddTemplate(importedPage, 0, 0);


                                document.Close();
                                writer.Close();
                            }
                            catch (Exception e)
                            {
                            }
                        }
                }
            }


            string[] files = GetFiles(@"" + newPath + "\\AthleteNameAdded");
            PdfSharp.Pdf.PdfDocument outputDocument = new PdfSharp.Pdf.PdfDocument();

            foreach (string file in files)
            {
                PdfSharp.Pdf.PdfDocument inputDocument = PdfSharp.Pdf.IO.PdfReader.Open(file, PdfDocumentOpenMode.Import);
                int count = inputDocument.PageCount;
                for (int idx = 0; idx < count; idx++)
                {
                    // Get the page from the external document...
                    PdfSharp.Pdf.PdfPage page = inputDocument.Pages[idx];
                    // ...and add it to the output document.
                    outputDocument.AddPage(page);
                }
            }

            // Save the document...
            string concatenatedFilePath = @"" + desktopPath + "\\PR_Cards\\";

            if (!System.IO.Directory.Exists(concatenatedFilePath))
            {
                System.IO.Directory.CreateDirectory(concatenatedFilePath);
            }
            string concatenatedFileName = concatenatedFilePath + "PR_Cards_For_" + meetInfo[0].Replace(' ', '_') + ".pdf";

            try
            {
                outputDocument.Save(concatenatedFileName);
                // ...and start a viewer.
                Process.Start(concatenatedFileName);
            }
            catch (Exception e3)
            {
                MessageBox.Show("Please close PDF documents.");
            }

            //empty the temporary folder
            Array.ForEach(Directory.GetFiles(@"" + newPath + "\\AthleteNameAdded\\"), File.Delete);
        }
示例#35
0
        public void zerlegePdfInEinzelseiten(string zuZerlegendeDatei)
        {
            try
            {
                FileInfo file = new FileInfo(zuZerlegendeDatei);
                string name = file.Name.Substring(0, file.Name.LastIndexOf("."));
                // we create a reader for a certain document
                PdfReader reader = new PdfReader(zuZerlegendeDatei);
                // we retrieve the total number of pages
                int n = reader.NumberOfPages;
                int digits = 1 + (n / 10);
                Document document;
                int pagenumber;
                string filename;

                for (int i = 0; i < n; i++)
                {
                    pagenumber = i + 1;
                    filename = pagenumber.ToString();
                    while (filename.Length < digits) filename = "0" + filename;
                    filename = "_" + filename + ".pdf";
                    // step 1: creation of a document-object
                    document = new Document(reader.GetPageSizeWithRotation(pagenumber));
                    // step 2: we create a writer that listens to the document
                    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(this.Unterverzeichnis + "\\" + name + filename, FileMode.Create));
                    // step 3: we open the document
                    document.Open();
                    PdfContentByte cb = writer.DirectContent;
                    PdfImportedPage page = writer.GetImportedPage(reader, pagenumber);
                    int rotation = reader.GetPageRotation(pagenumber);
                    if (rotation == 90 || rotation == 270)
                    {
                        cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(pagenumber).Height);
                    }
                    else
                    {
                        cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                    }
                    // step 5: we close the document
                    document.Close();
                }
            }
            catch
            {
                //MessageBox.Show("Welche Datei solles sein?");
            }
        }
示例#36
0
        private void Startbtn_Click(object sender, EventArgs e)
        {
            this.Startbtn.Enabled = false;
            this.Quitbtn.Enabled = false;
            ArrayList imagelist = new ArrayList();

            object A = this.AttachFiledgv.Rows[0].Cells["StartPage"].Value;
            if (A != null)
            {
                traystart = A.ToString();
            }

            object B = this.AttachFiledgv.Rows[0].Cells["EndPage"].Value;
            if (B != null)
            {
                trayend = B.ToString();
            }

            object C = this.AttachFiledgv.Rows[1].Cells["StartPage"].Value;
            if (C != null)
            {
                partstart = C.ToString();
            }
            object D = this.AttachFiledgv.Rows[1].Cells["EndPage"].Value;
            if (D != null)
            {
                partend = D.ToString();
            }

            object E = this.AttachFiledgv.Rows[2].Cells["StartPage"].Value;
            if (E != null)
            {
                materialstart = E.ToString();
            }
            object F = this.AttachFiledgv.Rows[2].Cells["EndPage"].Value;
            if (F != null)
            {
                materialend = F.ToString();
            }

            object G = this.AttachFiledgv.Rows[3].Cells["StartPage"].Value;
            if (G != null)
            {
                weightstart = G.ToString();
            }
            object H = this.AttachFiledgv.Rows[3].Cells["EndPage"].Value;
            if (H != null)
            {
                weightend = H.ToString();
            }

            object J = this.AttachFiledgv.Rows[4].Cells["StartPage"].Value;
            if (J != null)
            {
                flangestart = J.ToString();
            }
            object K = this.AttachFiledgv.Rows[4].Cells["EndPage"].Value;
            if (K != null)
            {
                flangend = K.ToString();
            }

            DownLoadFrontPage();

            string pdfTemplate = User.rootpath + "\\" + drawing + ".pdf";
            if (string.IsNullOrEmpty(pdfTemplate))
            {
                return;
            }
            string pdfnewfile = pdfTemplate.Substring(0, pdfTemplate.LastIndexOf('.'));
            string newFile = pdfnewfile + "new.pdf";
            PdfReader pdfReader = new PdfReader(pdfTemplate);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));
            AcroFields pdfFormFields = pdfStamper.AcroFields;
            string cardstr = GetImageName();
            string[] cardno = cardstr.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i <= cardno.Length - 1; i++)
            {
                string chartLoc = string.Format(@"\\ecdms\sign$\jpg\{0}.jpg", cardno[i]);
                imagelist.Add(chartLoc);
            }
            Single X = 0, Y = 43;
            if (imagelist.Count == 0)
            {
                MessageBox.Show("系统没有查询到相关电子签名,请与管理员联系");
                return;
            }
            else if(imagelist.Count == 4)
            {
                foreach (string item in imagelist)
                {
                    iTextSharp.text.Image chartImg = iTextSharp.text.Image.GetInstance(item);
                    iTextSharp.text.pdf.PdfContentByte underContent;
                    iTextSharp.text.Rectangle rect;

                    try
                    {
                        rect = pdfReader.GetPageSizeWithRotation(1);
                        X = 190;
                        Y += 13;
                        chartImg.ScalePercent(20);
                        chartImg.SetAbsolutePosition(X, Y);
                        underContent = pdfStamper.GetOverContent(1);
                        underContent.AddImage(chartImg);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }

            else if (imagelist.Count == 5)
            {
                for (int i = 0; i < imagelist.Count; i++)
                {
                    iTextSharp.text.Image chartImg = iTextSharp.text.Image.GetInstance(imagelist[i].ToString());
                    iTextSharp.text.pdf.PdfContentByte underContent;
                    iTextSharp.text.Rectangle rect;
                    rect = pdfReader.GetPageSizeWithRotation(1);
                    chartImg.ScalePercent(20);
                    if (i == 0)
                    {
                        X = 190;Y = 56;
                    }
                    else if (i == 1)
                    {
                        X = 190; Y = 69;
                    }
                    else if (i == 2)
                    {
                        X = 180; Y = 82;
                    }
                    else if (i == 3)
                    {
                        X = 205; Y = 82;
                    }
                    else if (i == 4)
                    {
                        X = 190; Y = 95;
                    }
                    chartImg.SetAbsolutePosition(X, Y);
                    underContent = pdfStamper.GetOverContent(1);
                    underContent.AddImage(chartImg);
                }
            }

            else if (imagelist.Count == 6)
            {
                for (int i = 0; i < imagelist.Count; i++)
                {
                    iTextSharp.text.Image chartImg = iTextSharp.text.Image.GetInstance(imagelist[i].ToString());
                    iTextSharp.text.pdf.PdfContentByte underContent;
                    iTextSharp.text.Rectangle rect;
                    rect = pdfReader.GetPageSizeWithRotation(1);
                    chartImg.ScalePercent(20);
                    if (i == 0)
                    {
                        X = 190; Y = 56;
                    }
                    else if (i == 1)
                    {
                        X = 180; Y = 69;
                    }
                    else if (i == 2)
                    {
                        X = 205; Y = 69;
                    }
                    else if (i == 3)
                    {
                        X = 180; Y = 82;
                    }
                    else if (i == 4)
                    {
                        X = 205; Y = 82;
                    }
                    else if (i == 5)
                    {
                        X = 190; Y = 95;
                    }
                    chartImg.SetAbsolutePosition(X, Y);
                    underContent = pdfStamper.GetOverContent(1);
                    underContent.AddImage(chartImg);
                }
            }

            InsertCharacteristics(pdfStamper, traystart, 340, 394);
            InsertCharacteristics(pdfStamper, trayend, 395, 394);

            InsertCharacteristics(pdfStamper, partstart, 340, 383);
            InsertCharacteristics(pdfStamper, partend, 395, 383);

            InsertCharacteristics(pdfStamper, materialstart, 340, 371);
            InsertCharacteristics(pdfStamper, materialend, 395, 371);

            InsertCharacteristics(pdfStamper, weightstart, 340, 360);
            InsertCharacteristics(pdfStamper, weightend, 395, 360);

            InsertCharacteristics(pdfStamper, flangestart, 340, 348);
            InsertCharacteristics(pdfStamper, flangend, 395, 348);

            pdfStamper.Close();
            pdfReader.Close();
            FileInfo fi = new FileInfo(pdfTemplate);
            fi.Delete();
            File.Move(newFile, pdfTemplate);

            Thread.Sleep(2000);
            string comText = "UPDATE SP_CREATEPDFDRAWING SET UPDATEDFRONTPAGE = :dfd WHERE PROJECTID = '" + projectid + "' AND DRAWINGNO = '" + drawing + "' and flag = 'Y'";
            InsertFrontPage.UpdateFrontPage(comText, User.rootpath + "\\" + drawing + ".pdf");
            FileInfo file = new FileInfo(pdfTemplate);
            file.Delete();

            this.Quitbtn.Enabled = true;
            this.Quitbtn.Text = "完成";
        }
示例#37
0
文件: Form1.cs 项目: cbaze19/bazepdf
        private void bCreatePDF_Click(Object sender, EventArgs e)
        {
            Match match = Regex.Match(tb_pages.Text, @"^(\d+|\d+-\d+)(,(\d+|\d+-\d+))*$");

            if (match.Success)
            {

                // Grab pages from text box
                List<int> pages = getNums(tb_pages.Text);

                PdfReader pdfReader = new PdfReader(openPDF_Dialog.FileName);
                int numberOfPages = pdfReader.NumberOfPages;
                bool page_validates = true;

                foreach (int p in pages)
                {
                    if (p > numberOfPages)
                    {
                        page_validates = false;
                    }
                }

                if (pages.Any() && page_validates)
                {

                    SaveFileDialog savePDF_Dialog = new SaveFileDialog();
                    savePDF_Dialog.Filter = "pdf files (*.pdf)|*.pdf";
                    savePDF_Dialog.FilterIndex = 2;
                    savePDF_Dialog.RestoreDirectory = false;

                    string save_path = "";

                    if (savePDF_Dialog.ShowDialog() == DialogResult.OK)
                    {
                        save_path = savePDF_Dialog.FileName;
                    }

                    pages.Sort();

                    PdfReader reader = null;
                    Document document = null;
                    PdfCopy pdfCopyProvider = null;
                    PdfImportedPage importedPage = null;

                    try
                    {
                        reader = new PdfReader(openPDF_Dialog.FileName);

                        string extracted_pdf_name = "";
                        if (String.IsNullOrEmpty(save_path))
                        {
                            // User willfully canceled saving... do nothing
                        }
                        else
                        {
                            extracted_pdf_name = save_path;

                            Console.Out.WriteLine(extracted_pdf_name);
                            document = new Document(reader.GetPageSizeWithRotation(pages[0]));

                            pdfCopyProvider = new PdfCopy(document, new FileStream(extracted_pdf_name, FileMode.Create));
                            document.Open();

                            foreach (int p in pages)
                            {
                                importedPage = pdfCopyProvider.GetImportedPage(reader, p);
                                pdfCopyProvider.AddPage(importedPage);
                            }

                            document.Close();
                            reader.Close();

                            tb_pages.Clear();

                            tb_pages.Enabled = false;
                            bCreatePDF.Enabled = false;
                            lPathPDF.Text = "No PDF File Selected...";

                            MessageBox.Show($"PDF Created at: {extracted_pdf_name}");

                            pdfViewer.LoadFile("meh.pdf");
                            selectedPages.Clear();
                            cbPageSelected.Checked = false;
                            bPrevPage.Enabled = false;
                            bNextPage.Enabled = false;
                            cbPageSelected.Enabled = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.Out.WriteLine(ex.Message);
                    }
                }
                else
                {
                    MessageBox.Show("ERROR: Invalid format in Pages entry.\n\nOnly numbers, dashes, and commas are accepted.\nCheck your date ranges to make sure they're correct.\nMake sure pages entered fall within source PDF page range.");
                }
            }
            else
            {
                MessageBox.Show("ERROR: Invalid format in Pages entry.\n\nOnly numbers, dashes, and commas are accepted.\nCheck your date ranges to make sure they're correct.\nMake sure pages entered fall within source PDF page range.");
            }
        }
        public ActionResult viewPRPdf(Int16 fiscalYear, Int16? coeID)
        {
            var allCoEs = db.CoEs.ToList();
            if (coeID != 0 && coeID != null)
            {
                allCoEs = allCoEs.Where(x => x.CoE_ID == coeID).ToList();
            }
            else
            {
                allCoEs = allCoEs.Where(x => x.CoE_ID != 0).ToList();
            }

            var allMaps = new List<Indicator_CoE_Maps>();
            allMaps = db.Indicator_CoE_Maps.ToList();
            ModelState.Clear();
            var viewModel = new PRViewModel
            {
                //allCoEs = db.CoEs.ToList(),
                allCoEs = allCoEs,
                allAnalysts = db.Analysts.ToList(),
                allMaps = allMaps,
                allFootnoteMaps = db.Indicator_Footnote_Maps.ToList(),
                allFootnotes = db.Footnotes.ToList(),
                Fiscal_Year = fiscalYear,
                Analyst_ID = null,
                allColors = db.Color_Types.ToList(),
            };

            HttpResponse httpResponse = this.HttpContext.ApplicationInstance.Context.Response;
            httpResponse.Clear();
            httpResponse.ContentType = "application/pdf";
            httpResponse.AddHeader("content-disposition", "attachment;filename=\"test.pdf\"");

            MemoryStream memoryStream = new MemoryStream();
            string apiKey = "2429a8e1-7cf6-4a77-9f7f-f4a85a9fcc14";
            var test = (this.RenderView("viewPRSimple", viewModel));
            string value = "<meta charset='UTF-8' />" + test;

            List<string> coeNotes;
            var topMargin = 6;
            if (allCoEs.FirstOrDefault(x => x.CoE_ID == coeID).CoE_Notes != null && allCoEs.FirstOrDefault(x => x.CoE_ID == coeID).CoE_Notes != "")
            {
                coeNotes = Regex.Matches(allCoEs.FirstOrDefault(x => x.CoE_ID == coeID).CoE_Notes, @"\[.*?\]").Cast<Match>().Select(m => m.Value.Substring(1, m.Value.Length - 2)).ToList();
                var coeNotesCount = coeNotes.Count();
                topMargin+=coeNotesCount * 5;
            }

            using (var client = new WebClient())
            {
                NameValueCollection options = new NameValueCollection();
                options.Add("apikey", apiKey);
                options.Add("value", value);
                options.Add("DisableJavascript", "false");
                options.Add("PageSize", "Legal");
                options.Add("UseLandscape", "true");
                options.Add("Zoom", "1.0");
                options.Add("MarginLeft", "2");
                options.Add("MarginTop", "10");
                options.Add("MarginBottomn", "5");
                options.Add("MarginRight", "2");
                //options.Add("HeaderUrl", this.HttpContext.ApplicationInstance.Server.MapPath("viewPRSimple_Header"));
                byte[] result = client.UploadValues("http://api.html2pdfrocket.com/pdf", options);
                //httpResponse.BinaryWrite(result);
                memoryStream.Write(result, 0, result.Length);
            }

            string picPath = this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/SHSheader.png");
            Image logo = Image.GetInstance(picPath);
            //string picPathOPEO = this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/logoOPEO.png");
            //Image logoOPEO = Image.GetInstance(picPathOPEO);
            string footerPath = this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/footer.png");
            Image footer = Image.GetInstance(footerPath);
            string picMonthlyPath = this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/Monthly.png");
            string picQuaterlyPath = this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/quaterly.png");
            string picNAPath = this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/na.png");
            string picTargetPath = this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/target.png");
            string picDraftPath = this.HttpContext.ApplicationInstance.Server.MapPath("~/App_Data/draft.png");
            Image picDraft = Image.GetInstance(picDraftPath);

            var pdfDocument  = new iTextSharp.text.Document();
            var outStream = new MemoryStream();
            var writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDocument, outStream);

            pdfDocument.Open();
            var reader = new iTextSharp.text.pdf.PdfReader(memoryStream.ToArray());

            for (var page = 1; page <= reader.NumberOfPages; page++)
            {
                pdfDocument.SetPageSize(reader.GetPageSizeWithRotation(page));
                pdfDocument.NewPage();
                var importedPage = writer.GetImportedPage(reader, page);
                var pageRotation = reader.GetPageRotation(page);
                var pageWidth = reader.GetPageSizeWithRotation(page).Width;
                var pageHeight = reader.GetPageSizeWithRotation(page).Height;
                switch (pageRotation)
                {
                    case 0:
                        writer.DirectContent.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0);
                        break;

                    case 90:
                        writer.DirectContent.AddTemplate(importedPage, 0, -1f, 1f, 0, 0, pageHeight);
                        break;

                    case 180:
                        writer.DirectContent.AddTemplate(
                            importedPage, -1f, 0, 0, -1f, pageWidth, pageHeight);
                        break;

                    case 270:
                        writer.DirectContent.AddTemplate(importedPage, 0, 1f, -1f, 0, pageWidth, 0);
                        break;
                }
                pdfDocument.SetPageSize(pdfDocument.PageSize);

                logo.Alignment = Element.ALIGN_CENTER;
                logo.ScalePercent(70,70);
                logo.SetAbsolutePosition(5, reader.GetPageSizeWithRotation(page).Height - logo.ScaledHeight-15);
                writer.DirectContent.AddImage(logo);

                var obj = db.CoEs.FirstOrDefault(x => x.CoE_ID == coeID);
                var type = obj.GetType();
                var isDraft = (bool)(type.GetProperty(FiscalYear.FYStrFull("FY_", fiscalYear) + "Draft").GetValue(obj, null) ?? false);
                if (isDraft)
                {
                    picDraft.Alignment = Element.ALIGN_CENTER;
                    picDraft.ScalePercent(70, 70);
                    picDraft.SetAbsolutePosition(reader.GetPageSizeWithRotation(page).Width / 4, 0);
                    writer.DirectContent.AddImage(picDraft);
                }

                //logoOPEO.Alignment = Element.ALIGN_CENTER;
                //logoOPEO.ScalePercent(20, 20);
                //logoOPEO.SetAbsolutePosition(reader.GetPageSizeWithRotation(page).Width - logoOPEO.ScaledWidth - 5, reader.GetPageSizeWithRotation(page).Height - logoOPEO.ScaledHeight - 5);
                //writer.DirectContent.AddImage(logoOPEO);

                if (page == 1)
                {
                    footer.Alignment = Element.ALIGN_CENTER;
                    footer.ScalePercent(45, 45);
                    footer.SetAbsolutePosition(reader.GetPageSizeWithRotation(page).Width - footer.ScaledWidth - 6, 10);
                    writer.DirectContent.AddImage(footer);
                }
            }

            writer.CloseStream = false;
            pdfDocument.Close();

            outStream.WriteTo(httpResponse.OutputStream);
            outStream.Close();
            httpResponse.End();

            return View(viewModel);
        }
示例#39
0
        static public bool ReplaceBarcode128(string input, string output, int page, string sourceCode, string newCode, bool displayText, int maxBarCodeCount = 5)
        {
            float scale = 3;
            float dpi   = 300;

            bool barCodeFinded = false;

            Barcode       barcodeNew = CreateBarcode(BarcodeType.Code128, newCode, displayText);
            BarcodeResult barcode    = null;

            using (var fs = new FileStream(output, FileMode.Create))
                using (var pdfReader = new iTextSharp.text.pdf.PdfReader(input))
                    using (var document = PdfiumViewer.PdfDocument.Load(input))
                    {
                        PdfStamper stamper = new PdfStamper(pdfReader, fs);

                        var           info  = document.GetInformation();
                        IList <SizeF> sizes = document.PageSizes;

                        // Если задана страница, то только в нёё вставим штрихкод, если не задана, то для всех страниц документа
                        int count;
                        if (page <= 0)
                        {
                            page  = 0;
                            count = document.PageCount;
                        }
                        else
                        {
                            // В Pdfium нумерация с 0-ля, а у нас приходит с 1-цы.
                            count = page;
                            page -= 1;
                        }
                        for (; page < count; page++)
                        {
                            int imageWidth           = (int)(sizes[page].Width * scale);
                            int imageHeight          = (int)(sizes[page].Height * scale);
                            System.Drawing.Image img = document.Render(page, imageWidth, imageHeight, dpi, dpi, PdfiumViewer.PdfRenderFlags.Grayscale);

                            for (int i = 0; i < maxBarCodeCount; i++)
                            {
                                barcode = BarcodeOperations.ScanCode128(img, input + ".png");
                                if (barcode != null)
                                {
                                    barCodeFinded = true;
                                    if (barcode.Code == sourceCode)
                                    {
                                        float offsetX       = barcode.Left / scale;
                                        float offsetY       = barcode.Top / scale;
                                        float width         = (barcode.Right - barcode.Left) / scale;
                                        float rotateDegrees = barcode.Orientation;

                                        // Преобразуем к 0-360 и уберем минимальные отклонения
                                        // if (rotateDegrees < 0) rotateDegrees += 360;
                                        // else if (rotateDegrees >= 360) rotateDegrees -= 360;
                                        // if (Math.Abs(rotateDegrees - 0) <= 4) rotateDegrees = 0;
                                        // if (Math.Abs(rotateDegrees - 90) <= 4) rotateDegrees = 90;
                                        // if (Math.Abs(rotateDegrees - 180) <= 4) rotateDegrees = 180;
                                        // if (Math.Abs(rotateDegrees - 270) <= 4) rotateDegrees = 270;

                                        iTextSharp.text.Rectangle pagesize = pdfReader.GetPageSizeWithRotation(page + 1);

                                        // Поскольку ось координат Y для img,bmp сверху вниз направлена и начало в верхнем левом угле,
                                        // а в pdf снизу вверх и в нижним левом угле, то преобразуем координаты
                                        offsetY       = pagesize.Height - offsetY;
                                        rotateDegrees = -rotateDegrees;

                                        PdfOperations.PlaceBarcode(stamper, barcodeNew, page + 1, offsetX, offsetY, width, rotateDegrees);
                                    }
                                    else
                                    {
                                        Console.WriteLine(BARCODE_DIFFERENT_FOUND + barcode.Code);
                                    }
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                        stamper.Close();
                    }

            return(barCodeFinded);
        }
示例#40
0
        /// <summary>
        /// Takes pages from two pdf files, and produces an output file
        /// whose odd pages are the contents of the first, and
        /// even pages are the contents of the second. Useful for
        /// merging front/back output from single sided scanners.
        /// </summary>
        /// <param name="oddPageFile">The file supplying odd numbered pages</param>
        /// <param name="evenPageFile">The file supplying even numbered pages</param>
        /// <param name="outputFile">The output file containing the merged pages</param>
        /// <param name="skipExtraPages">Set to true to skip any extra pages if
        ///                              one file is longer than the other</param>
        public void EvenOddMerge(String oddPageFile, String evenPageFile,
                                 String outputFile, bool skipExtraPages)
        {
            if (!String.IsNullOrEmpty(oddPageFile) && !String.IsNullOrWhiteSpace(oddPageFile) &&
                !String.IsNullOrEmpty(evenPageFile) && !String.IsNullOrWhiteSpace(evenPageFile) &&
                !String.IsNullOrEmpty(outputFile) && !String.IsNullOrWhiteSpace(outputFile))
            {
                var oddPageDocument  = new iTextSharpPDF.PdfReader(oddPageFile);
                var evenPageDocument = new iTextSharpPDF.PdfReader(evenPageFile);
                try
                {
                    iTextSharpText.Document mergedOutputDocument = null;
                    iTextSharpPDF.PdfCopy   mergedOutputFile     = null;

                    int lastPage = 0;
                    switch (skipExtraPages)
                    {
                    case (false):
                        lastPage = oddPageDocument.NumberOfPages;
                        if (evenPageDocument.NumberOfPages > oddPageDocument.NumberOfPages)
                        {
                            lastPage = evenPageDocument.NumberOfPages;
                        }
                        else
                        {
                            lastPage = oddPageDocument.NumberOfPages;
                        }
                        break;

                    case (true):
                        if (evenPageDocument.NumberOfPages < oddPageDocument.NumberOfPages)
                        {
                            lastPage = evenPageDocument.NumberOfPages;
                        }
                        else
                        {
                            lastPage = oddPageDocument.NumberOfPages;
                        }
                        break;
                    }

                    try
                    {
                        mergedOutputDocument = new iTextSharpText.Document();
                        mergedOutputFile     = new iTextSharpPDF.PdfCopy(mergedOutputDocument, new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite));
                        mergedOutputDocument.Open();
                        for (int loop = 1; loop <= lastPage; loop++)
                        {
                            // Extract and merge odd page
                            if (loop <= oddPageDocument.NumberOfPages)
                            {
                                mergedOutputDocument.SetPageSize(oddPageDocument.GetPageSizeWithRotation(loop));
                                mergedOutputFile.AddPage(mergedOutputFile.GetImportedPage(oddPageDocument, loop));
                            }
                            // Extract and merge even page
                            if (loop <= evenPageDocument.NumberOfPages)
                            {
                                mergedOutputDocument.SetPageSize(evenPageDocument.GetPageSizeWithRotation(loop));
                                mergedOutputFile.AddPage(mergedOutputFile.GetImportedPage(evenPageDocument, loop));
                            }
                        }
                    }
                    finally
                    {
                        if (mergedOutputDocument != null && mergedOutputDocument.IsOpen())
                        {
                            mergedOutputDocument.Close();
                        }
                        if (mergedOutputFile != null)
                        {
                            mergedOutputFile.Close();
                            mergedOutputFile.FreeReader(oddPageDocument);
                            mergedOutputFile.FreeReader(evenPageDocument);
                        }
                    }
                }
                catch
                {
                    try
                    {
                        File.Delete(outputFile);
                    }
                    catch { }
                    throw;
                }
                finally
                {
                    try
                    {
                        if (oddPageDocument != null)
                        {
                            oddPageDocument.Close();
                        }
                        oddPageDocument = null;
                    }
                    catch { }
                    try
                    {
                        if (evenPageDocument != null)
                        {
                            evenPageDocument.Close();
                        }
                        evenPageDocument = null;
                    }
                    catch { }
                }
            }
            else
            {
                if (String.IsNullOrEmpty(oddPageFile) || String.IsNullOrWhiteSpace(oddPageFile))
                {
                    throw new ArgumentNullException("oddPageFile", exceptionArgumentNullOrEmptyString);
                }
                if (String.IsNullOrEmpty(evenPageFile) || String.IsNullOrWhiteSpace(evenPageFile))
                {
                    throw new ArgumentNullException("evenPageFile", exceptionArgumentNullOrEmptyString);
                }
                if (String.IsNullOrEmpty(outputFile) || String.IsNullOrWhiteSpace(outputFile))
                {
                    throw new ArgumentNullException("outputFile", exceptionArgumentNullOrEmptyString);
                }
            }
        }
示例#41
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="inputFile">The PDF file to split</param>
 /// <param name="splitStartPages"></param>
 public void SplitPDF(String inputFile, SortedList <int, String> splitStartPages)
 {
     if (!String.IsNullOrEmpty(inputFile) &&
         !String.IsNullOrWhiteSpace(inputFile) &&
         splitStartPages != null &&
         splitStartPages.Count >= 2)
     {
         var inputDocument = new iTextSharpPDF.PdfReader(inputFile);
         // First split must begin with page 1
         // Last split must not be higher than last page
         if (splitStartPages.Keys[0] == 1 &&
             splitStartPages.Keys[splitStartPages.Count - 1] <= inputDocument.NumberOfPages)
         {
             int currentPage = 1;
             int firstPageOfSplit;
             int lastPageOfSplit;
             try
             {
                 for (int splitPoint = 0; splitPoint <= (splitStartPages.Count - 1); splitPoint++)
                 {
                     firstPageOfSplit = currentPage;
                     if (splitPoint < (splitStartPages.Count - 1))
                     {
                         lastPageOfSplit = splitStartPages.Keys[splitPoint + 1] - 1;
                     }
                     else
                     {
                         lastPageOfSplit = inputDocument.NumberOfPages;
                     }
                     iTextSharpText.Document splitDocument   = null;
                     iTextSharpPDF.PdfCopy   splitOutputFile = null;
                     try
                     {
                         splitDocument   = new iTextSharpText.Document();
                         splitOutputFile = new iTextSharpPDF.PdfCopy(splitDocument, new FileStream(splitStartPages.Values[splitPoint], FileMode.Create, FileAccess.ReadWrite));
                         splitDocument.Open();
                         for (int outputPage = firstPageOfSplit; outputPage <= lastPageOfSplit; outputPage++)
                         {
                             splitDocument.SetPageSize(inputDocument.GetPageSizeWithRotation(currentPage));
                             splitOutputFile.AddPage(splitOutputFile.GetImportedPage(inputDocument, currentPage));
                             currentPage++;
                         }
                     }
                     finally
                     {
                         if (splitDocument != null && splitDocument.IsOpen())
                         {
                             splitDocument.Close();
                         }
                         if (splitOutputFile != null)
                         {
                             splitOutputFile.Close();
                             splitOutputFile.FreeReader(inputDocument);
                         }
                         splitDocument   = null;
                         splitOutputFile = null;
                     }
                 }
             }
             catch
             {
                 // Cleanup any files that may have
                 // been written
                 foreach (KeyValuePair <int, String> split in splitStartPages)
                 {
                     try
                     {
                         File.Delete(split.Value);
                     }
                     catch { }
                 }
                 throw;
             }
             finally
             {
                 if (inputDocument != null)
                 {
                     inputDocument.Close();
                 }
             }
         }
         else
         {
             if (splitStartPages.Keys[splitStartPages.Count - 1] > inputDocument.NumberOfPages)
             {
                 throw new ArgumentOutOfRangeException("splitStartPages", String.Format("Final page number must be less than the number of pages ({0}). Passed value is {1}.", inputDocument.NumberOfPages, splitStartPages.Keys[splitStartPages.Count - 1]));
             }
             throw new ArgumentOutOfRangeException("splitStartPages", "First page number must be 1.");
         }
     }
     else
     {
         if (inputFile == null)
         {
             throw new ArgumentNullException("inputFile", exceptionArgumentNullOrEmptyString);
         }
         if (splitStartPages == null)
         {
             throw new ArgumentNullException("splitStartPages", exceptionArgumentNullOrEmptyString);
         }
         throw new ArgumentOutOfRangeException("splitStartPages", "Must contain at least two KeyValue pairs.");
     }
 }
示例#42
0
 public void Splite(string inputFileName, int pageSize)
 {
     int rotation = 0; 
     PdfReader pdfReader = new PdfReader(inputFileName); 
     string fileName = inputFileName.Substring(0, inputFileName.Length-4); 
     int totalPages  = pdfReader.NumberOfPages;
     int block = 1;
     for (int i = 1; i <= totalPages; block++)
     {
         int tail=block * pageSize;
         if (tail > totalPages) {
             tail = totalPages;
         }
         string newFileName = fileName + string.Format("[{0}-{1}].pdf", i,tail);
         FileStream fs = new FileStream(newFileName, FileMode.Create);
         Document newDocument = new Document();
         PdfWriter pdfWriter = PdfWriter.GetInstance(newDocument, fs);
         pdfWriter.CloseStream = true; 
         newDocument.Open();
         PdfContentByte pdfContentByte = pdfWriter.DirectContent;
         for (int j=1;j<=pageSize && i<=totalPages;j++,i++)
         {
            newDocument.SetPageSize(pdfReader.GetPageSizeWithRotation(i));
            newDocument.NewPage();
            PdfImportedPage importedPage = pdfWriter.GetImportedPage(pdfReader,i);
            rotation = pdfReader.GetPageRotation(i);
            pdfContentByte.AddTemplate(importedPage, 0, 0);
            if (rotation == 90 || rotation == 270)
            {
                pdfContentByte.AddTemplate(importedPage, 0, -1f, 1f, 0, 0, pdfReader.GetPageSizeWithRotation(i).Height);
            }
            else
            {
               pdfContentByte.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0);
            }  
         }
         fs.Flush();
         newDocument.Close();   
     }            
 }  
示例#43
0
 public void MergeFiles(string destinationFile, string[] sourceFiles)
 {
     int f = 0;
     PdfReader reader = new PdfReader(sourceFiles[f]);
     int n = reader.NumberOfPages;
     Document document = new Document(reader.GetPageSizeWithRotation(1));
     PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
     document.Open();
     PdfContentByte cb = writer.DirectContent;
     PdfImportedPage page;
     int rotation;
     while (f < sourceFiles.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);
             }
         }
         f++;
         if (f < sourceFiles.Length)
         {
             reader = new PdfReader(sourceFiles[f]);
             n = reader.NumberOfPages;
         }
     }
     document.Close();
 }
示例#44
0
        /// <summary>
        /// Splits the document and saves the contents to a new pdf.
        /// </summary>
        /// <param name="reader">The reader.</param>
        public void SplitDocument(PdfReader reader)
        {
            PdfWriter writer = Writer;
             _document.Open();
             PdfContentByte content = writer.DirectContent;

             for (int i = StartPage; i <= EndPage; i++)
             {
            PdfImportedPage page = writer.GetImportedPage(reader, i);
            Rectangle pageSize = reader.GetPageSizeWithRotation(i);
            _document.SetPageSize(pageSize);
            _document.NewPage();
            int rotation = reader.GetPageRotation(i);
            if (rotation == 90 || rotation == 270)
               content.AddTemplate(page, 0, -1f, 1f, 0, 0, pageSize.Height);
            else
               content.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
             }
        }
        private void addFilePages(Stream fileStream)
        {
            PdfReader reader = null;
            try
            {
                _fileNumber++;
                _attachmentsCount += copyAttachments(fileStream);
                fileStream = fileStream.ReopenForReading();
                reader = new PdfReader(fileStream);
                reader.ConsolidateNamedDestinations();

                addBookmark(reader);

                int numberOfPages = reader.NumberOfPages;
                for (int pageNumber = 1; pageNumber <= numberOfPages; pageNumber++)
                {
                    var size = reader.GetPageSizeWithRotation(pageNumber);
                    _document.SetPageSize(size);
                    _document.NewPage();
                    _overallPageNumber++;

                    var page = _writer.GetImportedPage(reader, pageNumber);
                    addContentToPage(reader, size, page);
                    _writer.AddPage(page);
                }

                var form = reader.AcroForm;
                if (form != null)
                    _writer.CopyAcroForm(reader);
            }
            finally
            {
                if (reader != null)
                    _writer.FreeReader(reader);
            }
        }
        /// <summary> 合併PDF檔(集合) </summary>
        /// <param name="fileList">欲合併PDF檔之集合(一筆以上)</param>
        /// <param name="outMergeFile">合併後的檔名</param>
        ///     /// <param name="isA4">A5纸张转A4</param>
        public static void mergePDFFiles(string[] fileList, string outMergeFile, bool isA4)
        {
            iTextSharp.text.pdf.PdfReader reader, reader1;
            Document document;

            if (isA4) //是否使用A4纸
            {
                //全用A4
                document = new Document();
            }
            else
            {
                reader1  = new PdfReader(fileList[0]);
                document = new Document(reader1.GetPageSizeWithRotation(1));
            }
            try
            {
                //删除已有文件
                bool b = true;
                if (File.Exists(outMergeFile))
                {
                    try { File.Delete(outMergeFile); }
                    catch (Exception) { b = false; }
                }
                if (b)
                {
                    //如果文件存在则覆盖,如果不存在则创建
                    PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outMergeFile, FileMode.Create));
                    document.Open();
                    PdfContentByte  cb = writer.DirectContent;
                    PdfImportedPage newPage;
                    //合并PDF文档
                    for (int i = 0; i < fileList.Length; i++)
                    {
                        reader = new iTextSharp.text.pdf.PdfReader(fileList[i]);
                        int iPageNum = reader.NumberOfPages;
                        for (int j = 1; j <= iPageNum; j++)
                        {
                            if (!isA4)
                            {
                                document.SetPageSize(reader.GetPageSizeWithRotation(1));
                            }
                            else
                            {
                                document.SetPageSize(reader.GetPageSizeWithRotation(1));
                            }
                            document.NewPage();
                            newPage = writer.GetImportedPage(reader, j);
                            int rotation = reader.GetPageRotation(1);
                            if (rotation == 90 || rotation == 270)
                            {
                                if (isA4)
                                {
                                    cb.AddTemplate(newPage, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(1).Height);
                                }
                                else
                                {
                                    cb.AddTemplate(newPage, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(1).Height);
                                }
                            }
                            else
                            {
                                cb.AddTemplate(newPage, 1f, 0, 0, 1f, 0, 0);
                            }
                        }
                    }
                }
            }
            finally
            {
                document.Close();
            }
        }
示例#47
0
        public Boolean MergePdfFiles(String[] pdfFiles, String outputPath)
        {
            //                                     Optional ByVal authorName As String = "", _
            //                                     Optional ByVal creatorName As String = "", _
            //                                     Optional ByVal subject As String = "", _
            //                                     Optional ByVal title As String = "", _
            //                                     Optional ByVal keywords As String = "")
            Boolean result   = false;
            int     pdfCount = 0;                        //'total input pdf file count
            int     f        = 0;                        //'pointer to current input pdf file
            string  fileName = String.Empty;             // 'current input pdf filename

            iTextSharp.text.pdf.PdfReader reader = null;
            int pageCount = 0;                                //'cureent input pdf page count

            iTextSharp.text.Document           pdfDoc = null; //   'the output pdf document
            iTextSharp.text.pdf.PdfWriter      writer = null;
            iTextSharp.text.pdf.PdfContentByte cb     = null;
            //    'Declare a variable to hold the imported pages
            iTextSharp.text.pdf.PdfImportedPage page = null;
            int  rotation         = 0;
            bool unethicalreading = false;

            //    'Declare a font to used for the bookmarks
            iTextSharp.text.Font bookmarkFont = iTextSharp.text.FontFactory.GetFont(iTextSharp.text.FontFactory.HELVETICA, 12, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLUE);

            // Try
            pdfCount = pdfFiles.Length;
            if (pdfCount > 1)
            {
                //            'Open the 1st pad using PdfReader object
                fileName = pdfFiles[f];
                reader   = new iTextSharp.text.pdf.PdfReader(fileName);
                // reader.
                iTextSharp.text.pdf.PdfReader.unethicalreading = unethicalreading;
                //            'Get page count
                pageCount = reader.NumberOfPages;

                //            'Instantiate an new instance of pdf document and set its margins. This will be the output pdf.
                //            'NOTE: bookmarks will be added at the 1st page of very original pdf file using its filename. The location
                //            'of this bookmark will be placed at the upper left hand corner of the document. So you'll need to adjust
                //            'the margin left and margin top values such that the bookmark won't overlay on the merged pdf page. The
                //            'unit used is "points" (72 points = 1 inch), thus in this example, the bookmarks' location is at 1/4 inch from
                //            'left and 1/4 inch from top of the page.

                pdfDoc = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1), 18, 18, 18, 18);
                //            'Instantiate a PdfWriter that listens to the pdf document
                writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, new System.IO.FileStream(outputPath, System.IO.FileMode.Create));    //added system
                //            'Set metadata and open the document
                // With pdfDoc
                pdfDoc.AddAuthor("");
                pdfDoc.AddCreationDate();
                pdfDoc.AddCreator("");
                pdfDoc.AddProducer();
                pdfDoc.AddSubject("");
                pdfDoc.AddTitle("");
                pdfDoc.AddKeywords("");
                pdfDoc.Open();
                //  End With
                //            'Instantiate a PdfContentByte object
                cb = writer.DirectContent;
                //            'Now loop thru the input pdfs
                while (f < pdfCount)
                {
                    //                'Declare a page counter variable
                    int i = 0;
                    //                'Loop thru the current input pdf's pages starting at page 1
                    while (i < pageCount)
                    {
                        i += 1;
                        //                    'Get the input page size
                        pdfDoc.SetPageSize(reader.GetPageSizeWithRotation(i));
                        //                    'Create a new page on the output document
                        pdfDoc.NewPage();

                        //                    'If it is the 1st page, we add bookmarks to the page
                        //                    'If i = 1 Then
                        //                    '    'First create a paragraph using the filename as the heading
                        //                    '    Dim para As New iTextSharp.text.Paragraph(IO.Path.GetFileName(fileName).ToUpper(), bookmarkFont)
                        //                    '    'Then create a chapter from the above paragraph
                        //                    '    Dim chpter As New iTextSharp.text.Chapter(para, f + 1)
                        //                    '    'Finally add the chapter to the document
                        //                    '    pdfDoc.Add(chpter)
                        //                    'End If

                        //                    'Now we get the imported page


                        page = writer.GetImportedPage(reader, i);
                        //                    'Read the imported page's rotation
                        rotation = reader.GetPageRotation(i);
                        //                    'Then add the imported page to the PdfContentByte object as a template based on the page's rotation
                        if (rotation == 90)
                        {
                            cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                        }
                        else
                        if (rotation == 270)
                        {
                            cb.AddTemplate(page, 0, 1.0F, -1.0F, 0, reader.GetPageSizeWithRotation(i).Width + 60, -30);
                        }
                        else
                        {
                            cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0);
                        }
                    } //End While 2

                    //                'Increment f and read the next input pdf file
                    f += 1;
                    if (f < pdfCount)
                    {
                        fileName  = pdfFiles[f];
                        reader    = new iTextSharp.text.pdf.PdfReader(fileName);
                        pageCount = reader.NumberOfPages;
                    } //   End If
                }        //end while 1
                //            'When all done, we close the document so that the pdfwriter object can write it to the output file
                pdfDoc.Close();
                result = true;
            }//        End If Principal
             //    Catch ex As Exception
             //        Throw New Exception(ex.Message)
             //    End Try

            return(result);
        }
示例#48
0
        private static bool Overlay(dynamic overlay, string filename)
        {
            string inputFile  = ServiceCfg.PdfModel;
            string cardFolder = Path.Combine(ServiceCfg.OutputFolderPath, @"pages\");

            if (!PdfManager.CheckFolder(cardFolder, true))
            {
                return(false);
            }
            string outFile = Path.Combine(cardFolder, "CTP_" + filename);

            //Creation du reader et du document pour lire le document PDF original
            PdfReader reader   = new PdfReader(inputFile);
            Document  inputDoc = new Document(reader.GetPageSizeWithRotation(1));

            using (FileStream fs = new FileStream(outFile, FileMode.Create))
            {
                //Creation du PDF Writer pour créer le nouveau Document PDF
                PdfWriter outputWriter = PdfWriter.GetInstance(inputDoc, fs);
                inputDoc.Open();
                //Creation du Content Byte pour tamponner le PDF writer
                PdfContentByte cb1 = outputWriter.DirectContent;

                //Obtien le document PDF à utiliser comme superposition
                PdfReader       overlayReader = new PdfReader(overlay);
                PdfImportedPage overLay       = outputWriter.GetImportedPage(overlayReader, 1);

                //Obtention de la rotation de page de superposition
                int overlayRotation = overlayReader.GetPageRotation(1);

                int n = reader.NumberOfPages;

                //liste des numéros de pages à marquer dans le modèle
                List <int> pagesList = GetModelPages2Overlay(n);

                int i = 1;
                while (i <= n)
                {
                    //S'assurer que la taille de la nouvelle page correspond à celle du document d'origine
                    inputDoc.SetPageSize(reader.GetPageSizeWithRotation(i));
                    inputDoc.NewPage();

                    PdfImportedPage page = outputWriter.GetImportedPage(reader, i);

                    int rotation = reader.GetPageRotation(i);

                    //Ajout de la page PDF originale avec la bonne rotation
                    if (rotation == 90 || rotation == 270)
                    {
                        cb1.AddTemplate(page, 0, -1f, 1f, 0, 0,
                                        reader.GetPageSizeWithRotation(i).Height);
                    }
                    else
                    {
                        //cb1.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                        cb1.AddTemplate(page, 0, 0, true);
                    }

                    //si la page en cours est à marquer
                    if (pagesList.Contains(i))
                    {
                        //Ajout de la superposition avec la bonne rotation
                        if (overlayRotation == 90 || overlayRotation == 270)
                        {
                            cb1.AddTemplate(overLay, 0, -1f, 1f, 0, 0,
                                            reader.GetPageSizeWithRotation(i).Height);
                        }
                        else
                        {
                            //cb1.AddTemplate(overLay, 1f, 0, 0, 1f, 0, 0);
                            cb1.AddTemplate(overLay, float.Parse(ServiceCfg.OverlayX.ToString()), float.Parse(ServiceCfg.OverlayY.ToString()), true);
                        }
                    }
                    //Increment de page
                    i++;
                }
                //Fermeture du fichier d'entrée
                inputDoc.Close();
                //on garde le fichier de sortie
                _lastPdf = outFile;
                //Fermeture du reader pour le fichier de superposition
                overlayReader.Close();
            }

            reader.Close();
            return(true);
        }
示例#49
0
    public byte[] AddSignatureAppearance(byte[] pdfToStamBytes, string stampString)
    {
        using (var ms = new MemoryStream())
        {
            try
            {
                var imageWidth  = 425;
                var imageHeight = 89;
                var fontSize    = 0;
                if (stampString.Length > 25)
                {
                    fontSize = 8;
                }
                else
                {
                    fontSize = 12;
                }

                //TODO: Make configurable
                string path           = "emptyPath";
                string xsdFileLinux   = @"/var/local/lawtrust/configs/signatureFont.ttf";
                string xsdFileWindows = @"C:/lawtrust/configs/signatureFont.ttf";

                if (File.Exists(xsdFileLinux))
                {
                    path = xsdFileLinux;
                }
                else if (File.Exists(xsdFileWindows))
                {
                    path = xsdFileWindows;
                }
                if (!path.Equals("emptyPath"))
                {
                    var reader   = new iTextSharp.text.pdf.PdfReader(pdfToStamBytes);
                    var stamper  = new iTextSharp.text.pdf.PdfStamper(reader, ms);
                    var rotation = reader.GetPageRotation(1);
                    var box      = reader.GetPageSizeWithRotation(1);
                    var bf       = BaseFont.CreateFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                    var pcb      = stamper.GetOverContent(1);
                    var f        = new Font(bf, fontSize);
                    var p        = new Phrase(stampString, f);

                    //TODO: Make coordinates configurable
                    if (rotation == 90)
                    {
                        //landscape
                        ColumnText.ShowTextAligned(pcb, Element.ALIGN_CENTER, p, 740, 10, 0);
                    }
                    else if (rotation == 180)
                    {
                        //normal PDF
                        ColumnText.ShowTextAligned(pcb, Element.ALIGN_CENTER, p, 500, 10, 0);
                    }
                    else if (rotation == 270)
                    {
                        //landscape
                        ColumnText.ShowTextAligned(pcb, Element.ALIGN_CENTER, p, 740, 10, 0);
                    }
                    else
                    {
                        //normal PDF
                        ColumnText.ShowTextAligned(pcb, Element.ALIGN_CENTER, p, 500, 10, 0);
                    }

                    pcb.SaveState();
                    stamper.Close();
                    reader.Close();
                    return(ms.ToArray());
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                //need error handling
                return(null);
            }
        }
    }
示例#50
0
        static void Main(string[] args)
        {
            // Changes \ to / in the path string
            string oldstr            = @"\";
            string newstr            = @"/";
            string pdf_path_original = string.Empty;

            // Tells the file path
            Console.WriteLine("FILE PATH: ");
            Console.OutputEncoding = Encoding.GetEncoding(932);
            Console.WriteLine("ファイル パス: ");
            pdf_path_original = Console.ReadLine();
            string pdf_path = pdf_path_original.Replace(oldstr, newstr);

            // Tells the file name
            Console.WriteLine(".pdf`s Name: ");
            Console.OutputEncoding = Encoding.GetEncoding(932);
            Console.WriteLine("ファイルの名前は: ");
            string pdf_file_name = Console.ReadLine();
            string path_n_name   = pdf_path + "/" + pdf_file_name + ".pdf";

            // Tells the file alignment
            Console.WriteLine("Text alignment: ");
            Console.OutputEncoding = Encoding.GetEncoding(932);
            Console.WriteLine("テキスト配置: ");
            Console.WriteLine("1: Left (左), and Right (右), or 2: Middle (真ん中)");
            string caseSwitch = Console.ReadLine();

            Console.WriteLine();


            // Tells the file start page and end page
            Console.WriteLine(".pdf`s Initial Page ");
            Console.OutputEncoding = Encoding.GetEncoding(932);
            Console.WriteLine("最初のページは: ");
            string startpage_string = Console.ReadLine();
            int    startpage        = Int32.Parse(startpage_string);

            Console.WriteLine(".pdf`s Last Page ");
            Console.OutputEncoding = Encoding.GetEncoding(932);
            Console.WriteLine("最後のページは: ");
            string endpage_string = Console.ReadLine();
            int    endpage        = Int32.Parse(endpage_string);

            // Creates blank pdf files
            for (int i = startpage; i <= endpage; i++)
            {
                string convi = i.ToString();
                // Creates a temp folder for the pdf files
                System.IO.Directory.CreateDirectory(pdf_path + "/" + "temp");
                System.IO.FileStream pdf_creator = new System.IO.FileStream(pdf_path + "/" + "temp" + "/" + convi + ".pdf", System.IO.FileMode.Create);
                pdf_creator.Close();
            }


            // Tells the attributes from the new pdf files, and the original pdf source
            iTextSharp.text.pdf.PdfReader       reader          = null;
            iTextSharp.text.Document            sourceDocument  = null;
            iTextSharp.text.pdf.PdfCopy         pdfCopyProvider = null;
            iTextSharp.text.pdf.PdfImportedPage importedPage    = null;

            reader         = new iTextSharp.text.pdf.PdfReader(path_n_name);
            sourceDocument = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(startpage));
            sourceDocument.Open();

            // Creates a .docx to receive the pdf's text
            Spire.Doc.Document word_doc = new Spire.Doc.Document();

            // Word doc formatting
            Spire.Doc.Section             word_doc_section        = word_doc.AddSection();
            Spire.Doc.Documents.Paragraph word_doc_paragraph      = word_doc_section.AddParagraph();
            Spire.Doc.Documents.Paragraph word_doc_paragraph_page = word_doc_section.AddParagraph();


            // Update those blank pdf files, inserting the copied pages into it
            try
            {
                for (int i = startpage; i <= endpage; i++)
                {
                    string convi = i.ToString();
                    pdfCopyProvider = new PdfCopy(sourceDocument, new System.IO.FileStream(pdf_path + "/" + "temp" + "/" + convi + ".pdf", System.IO.FileMode.Append));
                    sourceDocument.Open();
                    importedPage = pdfCopyProvider.GetImportedPage(reader, i);
                    pdfCopyProvider.AddPage(importedPage);
                }


                sourceDocument.Close();
                reader.Close();
            }


            // ERROR
            catch (Exception ex)
            {
                Console.WriteLine("Error! ");
                Console.OutputEncoding = Encoding.GetEncoding(932);
                Console.WriteLine("エラー ! ");
                throw ex;
            }


            // Collects the text without furigana from the listed pdf files
            switch (caseSwitch)
            {
            // case 1 reffers to the left and right alignments of the pdf text
            case "1":
                Console.WriteLine();
                for (int i = startpage; i <= endpage; i++)
                {
                    // the following refers to the int counter of pages being converted into string
                    string convi = i.ToString();
                    Console.OutputEncoding = Encoding.GetEncoding(932);
                    Console.WriteLine("今のページ: " + convi);
                    Console.WriteLine("Current Page: " + convi);

                    // the following refers to the bitmiracle api pdf to get the texts
                    using (BitMiracle.Docotic.Pdf.PdfDocument pdf_1 = new BitMiracle.Docotic.Pdf.PdfDocument(pdf_path + "/" + "temp" + "/" + convi + ".pdf"))
                    {
                        BitMiracle.Docotic.Pdf.PdfPage page = pdf_1.Pages[0];
                        foreach (PdfTextData data in page.GetWords())
                        {
                            if (data.FontSize > 6 && data.Position.X < 600)
                            {
                                string text = data.Text;
                                text.TrimEnd();
                                Console.OutputEncoding = Encoding.GetEncoding(932);
                                Console.WriteLine(text);
                                //word_builder.Writeln(text);
                                word_doc_paragraph.AppendText(text);
                            }
                        }
                        foreach (PdfTextData data in page.GetWords())
                        {
                            if (data.FontSize > 6 && data.Position.X > 600)
                            {
                                string text = data.Text;
                                text.TrimEnd();
                                Console.OutputEncoding = Encoding.GetEncoding(932);
                                Console.WriteLine(text);
                                word_doc_paragraph.AppendText(text);
                            }
                        }
                    }
                    // the following lines reffers to the space between pages of the pdf text
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine();
                    // the followin reffers to the extra lines on word text


                    word_doc_paragraph.AppendText("                                        ");
                    word_doc_paragraph.AppendText("CURRENT PAGE: " + convi);
                    word_doc_paragraph = word_doc_section.AddParagraph();
                    word_doc.Sections[0].Paragraphs[i].AppendBreak(BreakType.PageBreak);
                }

                break;


            // case 2 reffers to the alignment of the pdf text that is centralized
            case "2":
                Console.WriteLine();
                for (int i = startpage; i <= endpage; i++)
                {
                    // the following refers to the int counter of pages being converted into string
                    string convi = i.ToString();
                    Console.OutputEncoding = Encoding.GetEncoding(932);
                    Console.WriteLine("今のページ: " + convi);
                    Console.WriteLine("Current Page: " + convi);

                    // the following refers to the bitmiracle api pdf to get the texts
                    using (BitMiracle.Docotic.Pdf.PdfDocument pdf_1 = new BitMiracle.Docotic.Pdf.PdfDocument(pdf_path + "/" + "temp" + "/" + convi + ".pdf"))
                    {
                        BitMiracle.Docotic.Pdf.PdfPage page = pdf_1.Pages[0];
                        foreach (PdfTextData data in page.GetWords())
                        {
                            if (data.FontSize > 6)
                            {
                                string text = data.Text;
                                text.TrimEnd();
                                Console.OutputEncoding = Encoding.GetEncoding(932);
                                Console.WriteLine(text);
                                word_doc_paragraph.AppendText(text);
                            }
                        }
                    }
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine();
                    Console.WriteLine();

                    word_doc_paragraph.AppendText("                                        ");
                    word_doc_paragraph.AppendText("CURRENT PAGE: " + convi);
                    word_doc_paragraph = word_doc_section.AddParagraph();
                    word_doc.Sections[0].Paragraphs[i].AppendBreak(BreakType.PageBreak);
                }
                break;

            default:
                Console.OutputEncoding = Encoding.GetEncoding(932);
                Console.WriteLine("error! (エラー)");
                Console.ReadKey();
                break;
            }

            // The following refers to creating a .docx file, opening up the file and deleting the temp folder
            word_doc.SaveToFile(pdf_path + "/" + pdf_file_name + ".docx", FileFormat.Docx);
            System.IO.Directory.Delete(pdf_path + "/" + "temp", true);
            try
            {
                System.Diagnostics.Process.Start(pdf_path + "/" + pdf_file_name + ".docx");
            }
            catch
            {
                Console.WriteLine("Error! ");
                Console.OutputEncoding = Encoding.GetEncoding(932);
                Console.WriteLine("エラー ! ");
            }
        }
示例#51
0
        private void SetZnakWodny(string fileName)
        {
            iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(fileName);

            BaseFont baseFont;

            using (Stream fontStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ScanHelper.Resources.arial.ttf"))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    fontStream?.CopyTo(ms);
                    baseFont = BaseFont.CreateFont("arial.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED, BaseFont.CACHED, ms.ToArray(), null);
                }
            }

            using (MemoryStream memoryStream = new MemoryStream())
            {
                PdfStamper pdfStamper = new PdfStamper(pdfReader, memoryStream);

                for (int i = 1; i <= pdfReader.NumberOfPages; i++)
                {
                    iTextSharp.text.Rectangle pageRectangle = pdfReader.GetPageSizeWithRotation(i);

                    PdfContentByte pdfPageContents = pdfStamper.GetOverContent(i);

                    pdfPageContents.SaveState();

                    PdfGState state = new PdfGState {
                        FillOpacity = 0.5f, StrokeOpacity = 0.5f
                    };

                    pdfPageContents.SetGState(state);

                    pdfPageContents.BeginText();

                    pdfPageContents.SetFontAndSize(baseFont, 8f);
                    pdfPageContents.SetRGBColorFill(128, 128, 128);

                    ColumnText ctOperat    = new ColumnText(pdfPageContents);
                    Phrase     pOperatText = new Phrase(textBoxOperat.Text, new iTextSharp.text.Font(baseFont, 14f));
                    ctOperat.SetSimpleColumn(pOperatText, 10, pageRectangle.Height - 50, 150, pageRectangle.Height - 10, 14f, Element.ALIGN_LEFT);
                    ctOperat.Go();

                    ColumnText ctStopka = new ColumnText(pdfPageContents);
                    Phrase     myText   = new Phrase(Resources.stopkaKwidzyn, new iTextSharp.text.Font(baseFont, 8f));
                    ctStopka.SetSimpleColumn(myText, 0, 0, pageRectangle.Width, 50, 8f, Element.ALIGN_CENTER);
                    ctStopka.Go();

                    pdfPageContents.EndText();

                    pdfPageContents.RestoreState();
                }

                pdfStamper.Close();

                byte[] byteArray = memoryStream.ToArray();

                using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(byteArray, 0, byteArray.Length);
                }
            }

            pdfReader.Close();
        }
示例#52
0
        public byte[] MergeFiles(List<byte[]> sourceFiles)
        {
            var document = new Document();
            var output = new MemoryStream();

            // Initialize pdf writer
            var writer = PdfWriter.GetInstance(document, output);
            writer.PageEvent = new PdfPageEvents();

            // Open document to write
            document.Open();
            var content = writer.DirectContent;

            // Iterate through all pdf documents
            foreach (byte[] sourceFile in sourceFiles)
            {
                var reader = new PdfReader(sourceFile);
                var numberOfPages = reader.NumberOfPages;

                // Iterate through all pages
                for (var currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++)
                {
                    // Determine page size for the current page
                    document.SetPageSize(reader.GetPageSizeWithRotation(currentPageIndex));

                    // Create page
                    document.NewPage();
                    var importedPage = writer.GetImportedPage(reader, currentPageIndex);

                    // Determine page orientation
                    var pageOrientation = reader.GetPageRotation(currentPageIndex);
                    if ((pageOrientation == 90) || (pageOrientation == 270))
                    {
                        content.AddTemplate(importedPage, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(currentPageIndex).Height);
                    }
                    else
                    {
                        content.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0);
                    }
                }
            }

            document.Close();

            return output.GetBuffer();
        }
示例#53
0
 /// <summary>
 /// Extracts a range of pages from a PDF file,
 /// and writes them to a new file.
 /// </summary>
 /// <param name="inputFile">The PDF to extract pages from.</param>
 /// <param name="outputFile">The new file to write the extracted pages to.</param>
 /// <param name="firstPage">The first page to extract.</param>
 /// <param name="lastPage">The last page to extract.</param>
 /// <exception cref="ArgumentNullException"></exception>
 /// <exception cref="ArgumentOutOfRangeException"></exception>
 /// <remarks><see cref="FileStream"/> constructor exceptions may also be thrown.</remarks>
 public void ExtractPDFPages(String inputFile, String outputFile, int firstPage, int lastPage)
 {
     if (!String.IsNullOrEmpty(inputFile) && !String.IsNullOrWhiteSpace(inputFile) &&
         !String.IsNullOrEmpty(outputFile) && !String.IsNullOrWhiteSpace(outputFile) &&
         firstPage > 0 && lastPage > 0 &&
         lastPage >= firstPage)
     {
         var inputDocument = new iTextSharpPDF.PdfReader(inputFile);
         try
         {
             // Page numbers specified must not be greater
             // than the number of pages in the document
             if (firstPage <= inputDocument.NumberOfPages &&
                 lastPage <= inputDocument.NumberOfPages)
             {
                 iTextSharpText.Document extractOutputDocument = null;
                 iTextSharpPDF.PdfCopy   extractOutputFile     = null;
                 try
                 {
                     extractOutputDocument = new iTextSharpText.Document();
                     extractOutputFile     = new iTextSharpPDF.PdfCopy(extractOutputDocument, new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite));
                     extractOutputDocument.Open();
                     for (int loop = firstPage; loop <= lastPage; loop++)
                     {
                         extractOutputDocument.SetPageSize(inputDocument.GetPageSizeWithRotation(loop));
                         extractOutputFile.AddPage(extractOutputFile.GetImportedPage(inputDocument, loop));
                     }
                 }
                 finally
                 {
                     if (extractOutputDocument != null && extractOutputDocument.IsOpen())
                     {
                         extractOutputDocument.Close();
                     }
                     if (extractOutputFile != null)
                     {
                         extractOutputFile.Close();
                         extractOutputFile.FreeReader(inputDocument);
                     }
                 }
             }
             else
             {
                 if (firstPage > inputDocument.NumberOfPages)
                 {
                     throw new ArgumentOutOfRangeException("firstPage", String.Format(exceptionParameterCannotBeGreaterThan, "firstPage", "the number of pages in the document."));
                 }
                 throw new ArgumentOutOfRangeException("lastPage", String.Format(exceptionParameterCannotBeGreaterThan, "firstPage", "the number of pages in the document."));
             }
         }
         catch
         {
             try
             {
                 File.Delete(outputFile);
             }
             catch { }
             throw;
         }
         finally
         {
             if (inputDocument != null)
             {
                 inputDocument.Close();
             }
             inputDocument = null;
         }
     }
     else
     {
         if (String.IsNullOrEmpty(inputFile) || String.IsNullOrWhiteSpace(inputFile))
         {
             throw new ArgumentNullException("inputFile", exceptionArgumentNullOrEmptyString);
         }
         if (String.IsNullOrEmpty(outputFile) || String.IsNullOrWhiteSpace(outputFile))
         {
             throw new ArgumentNullException("outputFile", exceptionArgumentNullOrEmptyString);
         }
         if (firstPage < 1)
         {
             throw new ArgumentOutOfRangeException("firstPage", exceptionArgumentZeroOrNegative);
         }
         if (lastPage < 1)
         {
             throw new ArgumentOutOfRangeException("lastPage", exceptionArgumentZeroOrNegative);
         }
         if (lastPage < firstPage)
         {
             throw new ArgumentOutOfRangeException("lastPage", String.Format(exceptionParameterCannotBeLessThan, "lastPage", "firstPage"));
         }
     }
 }
示例#54
0
        protected static void mergePDFFiles(string destinationFile, string[] sourceFiles)
        {
            // source: http://stackoverflow.com/questions/6196124/merge-pdf-files

            int f = 0;
            String outFile = destinationFile;
            Document document = null;
            PdfCopy writer = null;
            string filePath = null;

            while (f < sourceFiles.Length) {
                // build pdf path
                filePath = sourceFiles[f];

                // Create a reader for a certain document
                if (File.Exists(filePath)) {
                    PdfReader reader = new PdfReader(filePath);

                    // Retrieve the total number of pages
                    int n = reader.NumberOfPages;

                    if (f == 0) {
                        // Step 1: Creation of a document-object
                        document = new Document(reader.GetPageSizeWithRotation(1));
                        // Step 2: Create a writer that listens to the document
                        writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create));
                        // Step 3: Open the document
                        document.Open();
                    }

                    // Step 4: Add content
                    PdfImportedPage page;
                    for (int i = 0; i < n; ) {
                        ++i;
                        page = writer.GetImportedPage(reader, i);
                        writer.AddPage(page);
                    }
                    PRAcroForm form = reader.AcroForm;
                    if (form != null)
                        writer.CopyAcroForm(reader);
                }

                ++f;
            }
            // Step 5: Close the document
            document.Close();

            // dispose
            document.Dispose();
            document = null;
        }
示例#55
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (openFile1.SafeFileName == "" || openFile2.SafeFileName == "")
            {
                MessageBox.Show("No haz seleccionado ningún PDF", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            MessageBox.Show("Se unira \"" + openFile1.SafeFileName + "\" con \"" + openFile2.SafeFileName + "\"");
            saveFile.Filter = "Adobe Acrobat Document PDF (*.pdf)|*.pdf";
            saveFile.FilterIndex = 1;
            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                MessageBox.Show("Se guardara en la siguiente ruta:\n" + saveFile.FileName);

                FileStream myStream = new FileStream(saveFile.FileName,FileMode.OpenOrCreate);

                PdfReader reader  = new PdfReader(openFile1.FileName);
                PdfReader reader2 = new PdfReader(openFile2.FileName);
                Document document = new Document(reader.GetPageSizeWithRotation(1));
                PdfCopy writer = new PdfCopy(document, myStream);
                document.Open();
                document.AddCreationDate();
                if (txtAutor.Text != null)
                {
                    document.AddAuthor(txtAutor.Text);
                }
                if (txtHeader.Text != null)
                {
                    document.AddHeader(txtHeader.Text, "Document");
                }
                if (txtKeywords.Text != null)
                {
                    document.AddKeywords(txtKeywords.Text);
                }

                document.AddProducer();

                if (txtTitulo.Text != null)
                {
                    document.AddTitle(txtTitulo.Text);
                }
                // Calculando incremento
                progressBar.Refresh();
                int incremento = (int)(100 / (reader.NumberOfPages + reader2.NumberOfPages));
                MessageBox.Show("Incremento es: " + incremento);
                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    writer.AddPage(writer.GetImportedPage(reader, i));
                    progressBar.PerformStep();
                    progressBar.Increment(++incremento);
                }
                progressBar.Increment(50);
                for (int i = 1; i <= reader2.NumberOfPages; i++)
                {
                    writer.AddPage(writer.GetImportedPage(reader2, i));
                    progressBar.PerformStep();
                }
                progressBar.Increment(100);
                document.Close();
            }
        }
示例#56
0
        static void test01(string file)
        {
            var db = RedisWrite.Db;

            if (!File.Exists(file))
            {
                return;
            }

            var reader = new iTextSharpPdf.PdfReader(file);

            reader.RemoveUnusedObjects();
            long fileSize = reader.FileLength;

            int currentPage = 1;

            var readerCopy = new iTextSharpPdf.PdfReader(file);

            readerCopy.RemoveUnusedObjects();
            readerCopy.RemoveAnnotations();
            readerCopy.RemoveFields();
            readerCopy.RemoveUsageRights();
            string CreationDate = "";

            foreach (KeyValuePair <string, string> KV in readerCopy.Info)
            {
                if (KV.Key == "CreationDate")
                {
                    CreationDate = KV.Value;
                }
                //readerCopy.Info.Remove(KV.Key);
            }

            //int headerSize = readerCopy.Metadata.Length;
            //string mt = Encoding.UTF8.GetString(readerCopy.Metadata);

            int max = reader.NumberOfPages;

            if (max > 5)
            {
                max = 2;
            }
            string key = DocumentStatic.buildId(max, fileSize);

            var obj = new Dictionary <string, object>()
            {
                { "id", long.Parse(key) },
                { "file_name", Path.GetFileNameWithoutExtension(file) },
                { "file_type", "pdf" },
                { "file_size", fileSize },
                { "file_created", CreationDate },
                { "page", max }
            };
            string jsonInfo = JsonConvert.SerializeObject(obj);
            var    bufInfo  = ASCIIEncoding.UTF8.GetBytes(jsonInfo);
            var    lsEntry  = new List <NameValueEntry>()
            {
                new NameValueEntry(0, LZ4.LZ4Codec.Encode(bufInfo, 0, bufInfo.Length))
            };

            for (int i = 1; i <= max; i++)
            {
                ////using (FileStream fs = new FileStream(@"C:\temp\" + i + "-.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
                ////{
                ////    using (var d = new iTextSharpText.Document())
                ////    {
                ////        using (var w = new iTextSharpPdf.PdfCopy(d, fs))
                ////        {
                ////            d.Open();
                ////            w.AddPage(w.GetImportedPage(reader, i));
                ////            d.Close();
                ////        }
                ////    }
                ////}

                using (var ms = new MemoryStream())
                {
                    var docCopy = new iTextSharpText.Document(reader.GetPageSizeWithRotation(currentPage));
                    //var pdfCopy = new iTextSharpPdf.PdfCopy(docCopy, new FileStream(@"C:\temp\" + i + "-.pdf", FileMode.Create));
                    var pdfCopy = new iTextSharpPdf.PdfCopy(docCopy, ms);
                    docCopy.Open();
                    var page = pdfCopy.GetImportedPage(readerCopy, currentPage);
                    pdfCopy.SetFullCompression();
                    pdfCopy.AddPage(page);
                    currentPage += 1;
                    //long len = ms.Length;
                    docCopy.Close();
                    pdfCopy.Close();
                    //m_app.RedisUpdate(key, i.ToString(), ms.ToArray());

                    lsEntry.Add(new NameValueEntry(i, ms.ToArray()));
                }
            }
            readerCopy.Close();
            reader.Close();
            string did = db.StreamAdd("BUF", lsEntry.ToArray(), key + "-0");
        }
        // based on example http://itextsharp.sourceforge.net/examples/Concat.cs
        public string ConcatFilesOld(List <string> files, string targetPath)
        {
            try
            {
                if (files.Count > 0)
                {
                    string file = files[0];
                    iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(GetFullPath(file));
                    int n = reader.NumberOfPages;
                    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(targetPath, System.IO.FileMode.Create));

                    reader.Close();
                    document.Open();
                    iTextSharp.text.pdf.PdfContentByte  cb = writer.DirectContent;
                    iTextSharp.text.pdf.PdfImportedPage page;
                    int rotation;
                    foreach (string sourceFile in files)
                    {
                        int i = 0;
                        iTextSharp.text.pdf.PdfReader reader2 = new iTextSharp.text.pdf.PdfReader(GetFullPath(sourceFile));
                        n = reader2.NumberOfPages;
                        while (i < n)
                        {
                            i++;
                            document.SetPageSize(reader2.GetPageSizeWithRotation(i));
                            document.NewPage();
                            page     = writer.GetImportedPage(reader2, i);
                            rotation = reader2.GetPageRotation(i);
                            if (rotation == 90)
                            {
                                cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader2.GetPageSizeWithRotation(i).Height);
                            }
                            else if ((rotation == 270))
                            {
                                cb.AddTemplate(page, 0f, 1f, -1f, 0f, reader2.GetPageSizeWithRotation(i).Width, 0f);
                            }
                            else
                            {
                                cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                            }
                        }

                        writer.FreeReader(reader2);
                        reader2.Close();
                    }

                    if (document.IsOpen())
                    {
                        document.CloseDocument();
                        document.Close();
                    }
                    return("");
                }
                else
                {
                    return("No files to process, use AddFile method");
                }
            }
            catch (Exception e)
            {
                return(e.Message);
            }
        }
            public void AddAnnotation(PdfAnnotation annot)
            {
                var allAnnots = new ArrayList();

                if (annot.IsForm())
                {
                    var field = (PdfFormField)annot;
                    if (field.Parent != null)
                    {
                        return;
                    }

                    expandFields(field, allAnnots);
                    if (_cstp.FieldTemplates == null)
                    {
                        _cstp.FieldTemplates = new Hashtable();
                    }
                }
                else
                {
                    allAnnots.Add(annot);
                }

                for (var k = 0; k < allAnnots.Count; ++k)
                {
                    annot = (PdfAnnotation)allAnnots[k];
                    if (annot.IsForm())
                    {
                        if (!annot.IsUsed())
                        {
                            var templates = annot.Templates;
                            if (templates != null)
                            {
                                foreach (var tpl in templates.Keys)
                                {
                                    _cstp.FieldTemplates[tpl] = null;
                                }
                            }
                        }
                        var field = (PdfFormField)annot;
                        if (field.Parent == null)
                        {
                            addDocumentField(field.IndirectReference);
                        }
                    }
                    if (annot.IsAnnotation())
                    {
                        var      pdfobj = PdfReader.GetPdfObject(_pageN.Get(PdfName.Annots), _pageN);
                        PdfArray annots = null;
                        if (pdfobj == null || !pdfobj.IsArray())
                        {
                            annots = new PdfArray();
                            _pageN.Put(PdfName.Annots, annots);
                        }
                        else
                        {
                            annots = (PdfArray)pdfobj;
                        }

                        annots.Add(annot.IndirectReference);
                        if (!annot.IsUsed())
                        {
                            var rect = (PdfRectangle)annot.Get(PdfName.Rect);
                            if (rect != null && (rect.Left.ApproxNotEqual(0) || rect.Right.ApproxNotEqual(0) || rect.Top.ApproxNotEqual(0) || rect.Bottom.ApproxNotEqual(0)))
                            {
                                var rotation = _reader.GetPageRotation(_pageN);
                                var pageSize = _reader.GetPageSizeWithRotation(_pageN);
                                switch (rotation)
                                {
                                case 90:
                                    annot.Put(PdfName.Rect, new PdfRectangle(
                                                  pageSize.Top - rect.Bottom,
                                                  rect.Left,
                                                  pageSize.Top - rect.Top,
                                                  rect.Right));
                                    break;

                                case 180:
                                    annot.Put(PdfName.Rect, new PdfRectangle(
                                                  pageSize.Right - rect.Left,
                                                  pageSize.Top - rect.Bottom,
                                                  pageSize.Right - rect.Right,
                                                  pageSize.Top - rect.Top));
                                    break;

                                case 270:
                                    annot.Put(PdfName.Rect, new PdfRectangle(
                                                  rect.Bottom,
                                                  pageSize.Right - rect.Left,
                                                  rect.Top,
                                                  pageSize.Right - rect.Right));
                                    break;
                                }
                            }
                        }
                    }
                    if (!annot.IsUsed())
                    {
                        annot.SetUsed();
                        _cstp.AddToBody(annot, annot.IndirectReference);
                    }
                }
            }
示例#59
-1
 /// <summary>
 /// Concatenates two or more PDF files into one file.
 /// </summary>
 /// <param name="inputFiles">A string array containing the names of the pdf files to concatenate</param>
 /// <param name="outputFile">Name of the concatenated file.</param>
 public void ConcatenatePDFFiles(String[] inputFiles, String outputFile)
 {
     if (inputFiles != null && inputFiles.Length > 0)
     {
         if (!String.IsNullOrEmpty(outputFile) && !String.IsNullOrWhiteSpace(outputFile))
         {
             var concatDocument = new iTextSharpText.Document();
             var outputCopy = new iTextSharpPDF.PdfCopy(concatDocument, new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite));
             concatDocument.Open();
             try
             {
                 for (int loop = 0; loop <= inputFiles.GetUpperBound(0); loop++)
                 {
                     var inputDocument = new iTextSharpPDF.PdfReader(inputFiles[loop]);
                     for (int pageLoop = 1; pageLoop <= inputDocument.NumberOfPages; pageLoop++)
                     {
                         concatDocument.SetPageSize(inputDocument.GetPageSizeWithRotation(pageLoop));
                         outputCopy.AddPage(outputCopy.GetImportedPage(inputDocument, pageLoop));
                     }
                     inputDocument.Close();
                     outputCopy.FreeReader(inputDocument);
                     inputDocument = null;
                 }
                 concatDocument.Close();
                 outputCopy.Close();
             }
             catch
             {
                 if (concatDocument != null && concatDocument.IsOpen()) concatDocument.Close();
                 if (outputCopy != null) outputCopy.Close();
                 if (File.Exists(outputFile))
                 {
                     try
                     {
                         File.Delete(outputFile);
                     }
                     catch { }
                 }
                 throw;
             }
         }
         else
         {
             throw new ArgumentNullException("outputFile", exceptionArgumentNullOrEmptyString);
         }
     }
     else
     {
         throw new ArgumentNullException("inputFiles", exceptionArgumentNullOrEmptyString);
     }
 }