コード例 #1
0
        static void Main(string[] args)
        {
            if (args == null || args.Length < 2)
            {
                System.Console.WriteLine("Usage: " + AppDomain.CurrentDomain.FriendlyName + " <original PDF filename> <watermark text> [new PDF filename]" + Environment.NewLine +
                                         "  For example: " + AppDomain.CurrentDomain.FriendlyName + " myDoc.pdf \"This is a Draft\"");
            }
            else
            {
                string origName     = args[0];
                string watermarkTxt = args[1];
                if (!System.IO.File.Exists(origName))
                {
                    System.Console.WriteLine("Error: cannot find the original PDF file(" + origName + "). Please correct the filename or the path and try again.");
                }
                else
                {
                    PDDocument origDoc  = PDDocument.load(new java.io.File(origName)); // NOTE: PDDocument.load() only takes java.io.File, not System.IO.File from C#.Net
                    PDPageTree allPages = origDoc.getPages();
                    PDFont     font     = PDType1Font.HELVETICA_BOLD;
                    for (int i = 0, len = allPages.getCount(); i < len; ++i)
                    {
                        PDPage pg = (PDPage)allPages.get(i);
                        addWatermarkText(origDoc, pg, font, "This is a draft!!!");
                    }

                    origDoc.save("watermarked_" + origName);
                    origDoc.close();
                }
            }
        }
コード例 #2
0
ファイル: PDFMerger.cs プロジェクト: jehan2898/root
 private void GetSubFolders(DirectoryInfo sourceDirectoryInfo)
 {
     DirectoryInfo[] directories = sourceDirectoryInfo.GetDirectories();
     for (int i = 0; i < (int)directories.Length; i++)
     {
         this.GetSubFolders(directories[i]);
     }
     this.mergeUtility = new PDFMergerUtility();
     FileInfo[] files = sourceDirectoryInfo.GetFiles("*.pdf");
     for (int j = 0; j < (int)files.Length; j++)
     {
         FileInfo fileInfo = files[j];
         this.mergeUtility.addSource(fileInfo.FullName);
     }
     if (!PDFHelper.AddStamp)
     {
         this.mergeUtility.setDestinationFileName(Path.Combine(this.outputFolder, string.Concat(sourceDirectoryInfo.Name, ".pdf")));
         this.mergeUtility.mergeDocuments();
     }
     else
     {
         string str = Path.Combine(Path.GetTempPath(), string.Concat("aquaforest\\pdftoolkit\\", Path.GetRandomFileName(), ".pdf"));
         this.mergeUtility.setDestinationFileName(str);
         this.mergeUtility.mergeDocuments();
         PDDocument pDDocument = PDDocument.load(new java.io.File(str));
         pDDocument = PDFHelper.AddTrialStampIfNecessary(pDDocument);
         pDDocument.save(Path.Combine(this.outputFolder, string.Concat(sourceDirectoryInfo.Name, ".pdf")));
         if (System.IO.File.Exists(str))
         {
             System.IO.File.Delete(str);
         }
     }
 }
コード例 #3
0
ファイル: PDFMerger.cs プロジェクト: jehan2898/root
 public void MergePDFs(List <string> sourcePDFs, string outputFile)
 {
     PDFHelper.DisplayTrialPopupIfNecessary();
     foreach (string sourcePDF in sourcePDFs)
     {
         this.mergeUtility.addSource(sourcePDF);
     }
     if (!PDFHelper.AddStamp)
     {
         this.mergeUtility.setDestinationFileName(outputFile);
         this.mergeUtility.mergeDocuments();
     }
     else
     {
         string str = Path.Combine(Path.GetTempPath(), string.Concat(Path.GetRandomFileName(), ".pdf"));
         this.mergeUtility.setDestinationFileName(str);
         this.mergeUtility.mergeDocuments();
         PDDocument pDDocument = PDDocument.load(new java.io.File(str));
         pDDocument = PDFHelper.AddTrialStampIfNecessary(pDDocument);
         pDDocument.save(outputFile);
         if (pDDocument != null)
         {
             pDDocument.close();
         }
         if (System.IO.File.Exists(str))
         {
             System.IO.File.Delete(str);
         }
     }
 }
コード例 #4
0
ファイル: PDFSplitter.cs プロジェクト: jehan2898/root
 private void Split(int start, int end, int repeatEvery)
 {
     if (this.CheckOutput())
     {
         PDFHelper.DisplayTrialPopupIfNecessary();
         try
         {
             Splitter splitter = new Splitter();
             splitter.setStartPage(start);
             splitter.setEndPage(end);
             splitter.setSplitAtPage(repeatEvery);
             List list = splitter.split(this.pdfDocument.PDFBoxDocument);
             for (int i = 0; i < list.size(); i++)
             {
                 PDDocument pDDocument = PDFHelper.AddTrialStampIfNecessary((PDDocument)list.@get(i));
                 string     str        = string.Format("{0} [{1}].pdf", this.OutputFileName, i);
                 pDDocument.save(Path.Combine(this.OutputFilePath, str));
             }
         }
         catch (Exception exception1)
         {
             Exception exception = exception1;
             throw new PDFToolkitException(exception.Message, exception.InnerException);
         }
     }
 }
 public void export(String ZUGFeRDfilename)
 {
     try
     {
         doc.save(ZUGFeRDfilename);
     }
     catch (Exception e)
     {
         // TODO Auto-generated catch block
         Debug.Print(e.StackTrace);
     }
 }
コード例 #6
0
ファイル: PDFOverlay.cs プロジェクト: jehan2898/root
        public void ApplyOverlay(string outputFile)
        {
            PDFHelper.DisplayTrialPopupIfNecessary();
            Map     hashMap = new HashMap();
            Overlay overlay = new Overlay();

            overlay.setInputPDF(this.overlayDestination.PDFBoxDocument);
            overlay.setAllPagesOverlayPDF(this.overlay.PDFBoxDocument);
            overlay.setOverlayPosition(Overlay.Position.FOREGROUND);
            PDDocument pDDocument = overlay.overlay(hashMap);

            if (!PDFHelper.AddStamp)
            {
                pDDocument.save(outputFile);
            }
            else
            {
                pDDocument = PDFHelper.AddTrialStampIfNecessary(pDDocument);
                pDDocument.save(outputFile);
            }
            pDDocument.close();
            overlay.close();
        }
コード例 #7
0
ファイル: PDFSplitter.cs プロジェクト: jehan2898/root
 public void SplitByTopLevelBookmarks()
 {
     if (this.CheckOutput())
     {
         PDFHelper.DisplayTrialPopupIfNecessary();
         try
         {
             PDDocumentCatalog documentCatalog = this.pdfDocument.PDFBoxDocument.getDocumentCatalog();
             PDDocumentOutline documentOutline = documentCatalog.getDocumentOutline();
             if (documentOutline != null)
             {
                 PDOutlineItem firstChild = documentOutline.getFirstChild();
                 PDPageTree    pages      = documentCatalog.getPages();
                 List <int>    nums       = new List <int>();
                 while (firstChild != null)
                 {
                     PDPage pDPage = firstChild.findDestinationPage(this.pdfDocument.PDFBoxDocument);
                     nums.Add(pages.indexOf(pDPage));
                     firstChild = firstChild.getNextSibling();
                 }
                 nums.Add(pages.getCount());
                 for (int i = 0; i < nums.Count - 1; i++)
                 {
                     int        item       = nums[i];
                     int        num        = nums[i + 1];
                     PDDocument pDDocument = new PDDocument();
                     for (int j = item; j < num; j++)
                     {
                         pDDocument.addPage(this.pdfDocument.PDFBoxDocument.getPage(j));
                     }
                     pDDocument = PDFHelper.AddTrialStampIfNecessary(pDDocument);
                     string str = string.Format("{0} [{1}].pdf", this.OutputFileName, i);
                     pDDocument.save(Path.Combine(this.OutputFilePath, str));
                     pDDocument.close();
                 }
             }
             else
             {
                 Console.WriteLine("This document does not contain any bookmarks.");
             }
         }
         catch (Exception exception1)
         {
             Exception exception = exception1;
             throw new PDFToolkitException(exception.Message, exception.InnerException);
         }
     }
 }
コード例 #8
0
        /// <summary>
        /// Save specifical page to file
        /// </summary>
        /// <param name="PageNumbers"></param>
        /// <param name="sourceFilePath"></param>
        /// <param name="outputFilePath"></param>
        public static void ExtractToSingleFile(int[] PageNumbers, string sourceFilePath, string outputFilePath)
        {
            var originalDocument = PDDocument.load(sourceFilePath);
            var originalCatalog  = originalDocument.getDocumentCatalog();

            java.util.List sourceDocumentPages = originalCatalog.getAllPages();
            var            newDocument         = new PDDocument();

            foreach (var pageNumber in PageNumbers)
            {
                // Page numbers are 1-based, but PDPages are contained in a zero-based array:
                int pageIndex = pageNumber - 1;
                newDocument.addPage((PDPage)sourceDocumentPages.get(pageIndex));
            }
            newDocument.save(outputFilePath);
        }
コード例 #9
0
ファイル: PDFSplitter.cs プロジェクト: jehan2898/root
        public void SplitByPageRanges(string pageRanges)
        {
            int num;
            int num1;
            int num2;
            int num3;

            if (this.CheckOutput())
            {
                PDFHelper.DisplayTrialPopupIfNecessary();
                try
                {
                    string[] strArrays  = pageRanges.Split(new char[] { ',' });
                    List     list       = IteratorUtils.toList(this.pdfDocument.PDFBoxDocument.getPages().iterator());
                    int      num4       = list.size();
                    string[] strArrays1 = strArrays;
                    for (int i = 0; i < (int)strArrays1.Length; i++)
                    {
                        string str = strArrays1[i];
                        if (this.ConfigureRange(str, num4, out num, out num1, out num2, out num3))
                        {
                            List       list1      = list.subList(num, num1);
                            PDDocument pDDocument = new PDDocument();
                            for (int j = num2; j < list1.size(); j = j + num3)
                            {
                                PDPage pDPage = (PDPage)list1.@get(j);
                                pDPage.getResources();
                                pDDocument.addPage(pDPage);
                            }
                            pDDocument = PDFHelper.AddTrialStampIfNecessary(pDDocument);
                            string str1 = string.Format("{0} [{1}].pdf", this.OutputFileName, str);
                            pDDocument.save(Path.Combine(this.OutputFilePath, str1));
                        }
                        else
                        {
                            Console.WriteLine("Invalid range: {0}", str);
                        }
                    }
                }
                catch (Exception exception1)
                {
                    Exception exception = exception1;
                    throw new PDFToolkitException(exception.Message, exception.InnerException);
                }
            }
        }
コード例 #10
0
ファイル: PDFSplitter.cs プロジェクト: jehan2898/root
        private void SplitByRepeatingPageRanges(string pageRange, int repeatEvery, PDPageTree allPages, int pageCount, string suffix)
        {
            int num;
            int num1;
            int num2;
            int num3;

            if (this.ConfigureRange(pageRange, pageCount, out num, out num1, out num2, out num3))
            {
                List       list       = IteratorUtils.toList(allPages.iterator());
                List       list1      = list.subList(num, num1);
                PDDocument pDDocument = new PDDocument();
                for (int i = num2; i < list1.size(); i = i + num3)
                {
                    pDDocument.addPage((PDPage)list1.@get(i));
                }
                pDDocument = PDFHelper.AddTrialStampIfNecessary(pDDocument);
                string str = string.Format("{0} [{1}].pdf", this.OutputFileName, this.splitCounter);
                pDDocument.save(Path.Combine(this.OutputFilePath, str));
                if (repeatEvery > 0)
                {
                    num  = num + repeatEvery + 1;
                    num1 = num1 + repeatEvery;
                    if (num <= pageCount)
                    {
                        if (num1 > pageCount)
                        {
                            num1 = pageCount;
                        }
                        this.splitCounter = this.splitCounter + 1;
                        string str1 = string.Format("{0}-{1}{2}", num, num1, suffix);
                        this.SplitByRepeatingPageRanges(str1, repeatEvery, allPages, pageCount, suffix);
                    }
                }
            }
            else
            {
                Console.WriteLine("Invalid page range.");
            }
        }
コード例 #11
0
ファイル: PDFMerger.cs プロジェクト: jehan2898/root
        public void MergeFolderOfPDFs(string sourceFolder, string outputFile, bool processSubFolders)
        {
            FileInfo[] fileInfoArray;
            PDFHelper.DisplayTrialPopupIfNecessary();
            DirectoryInfo directoryInfo = new DirectoryInfo(sourceFolder);

            fileInfoArray = (!processSubFolders ? directoryInfo.GetFiles("*.pdf") : directoryInfo.GetFiles("*.pdf", SearchOption.AllDirectories));
            FileInfo[] fileInfoArray1 = fileInfoArray;
            for (int i = 0; i < (int)fileInfoArray1.Length; i++)
            {
                FileInfo fileInfo = fileInfoArray1[i];
                this.mergeUtility.addSource(fileInfo.FullName);
            }
            if (!PDFHelper.AddStamp)
            {
                this.mergeUtility.setDestinationFileName(outputFile);
                this.mergeUtility.mergeDocuments();
            }
            else
            {
                string str = Path.Combine(Path.GetTempPath(), string.Concat("aquaforest\\pdftoolkit\\", Path.GetRandomFileName(), ".pdf"));
                this.mergeUtility.setDestinationFileName(str);
                this.mergeUtility.mergeDocuments();
                PDDocument pDDocument = PDDocument.load(new java.io.File(str));
                pDDocument = PDFHelper.AddTrialStampIfNecessary(pDDocument);
                pDDocument.save(outputFile);
                if (pDDocument != null)
                {
                    pDDocument.close();
                }
                if (System.IO.File.Exists(str))
                {
                    System.IO.File.Delete(str);
                }
            }
        }
コード例 #12
0
ファイル: PDFSecurity.cs プロジェクト: jehan2898/root
 public void SecurePDF(PDFDocument sourcePDF, string outputFile)
 {
     PDFHelper.DisplayTrialPopupIfNecessary();
     try
     {
         AccessPermission accessPermission = new AccessPermission();
         accessPermission.setCanAssembleDocument(this.Permission.AllowAssembly);
         accessPermission.setCanExtractContent(this.Permission.AllowExtractContents);
         accessPermission.setCanExtractForAccessibility(this.Permission.AllowExtractForAccessibility);
         accessPermission.setCanFillInForm(this.Permission.AllowFillInForm);
         accessPermission.setCanModify(this.Permission.AllowModifyContents);
         accessPermission.setCanModifyAnnotations(this.Permission.AllowModifyAnnotations);
         accessPermission.setCanPrint(this.Permission.AllowPrinting);
         accessPermission.setCanPrintDegraded(this.Permission.AllowDegradedPrinting);
         StandardProtectionPolicy standardProtectionPolicy = new StandardProtectionPolicy(this.OwnerPassword, this.UserPassword, accessPermission);
         if (!PDFHelper.AddStamp)
         {
             sourcePDF.PDFBoxDocument.protect(standardProtectionPolicy);
             sourcePDF.PDFBoxDocument.save(outputFile);
             sourcePDF.PDFBoxDocument.close();
         }
         else
         {
             PDDocument pDFBoxDocument = sourcePDF.PDFBoxDocument;
             pDFBoxDocument = PDFHelper.AddTrialStampIfNecessary(pDFBoxDocument);
             pDFBoxDocument.protect(standardProtectionPolicy);
             pDFBoxDocument.save(outputFile);
             pDFBoxDocument.close();
         }
     }
     catch (Exception exception1)
     {
         Exception exception = exception1;
         throw new PDFToolkitException(exception.Message, exception);
     }
 }
コード例 #13
0
ファイル: PublisherToPDF.cs プロジェクト: jehan2898/root
        public bool ConvertToPDF(DocumentSettings settings, string outputFileName)
        {
            bool docStructureTags;
            bool bitmapNonEmbeddableFonts;
            bool flag;

            try
            {
                string tempPath = Path.GetTempPath();
                Guid   guid     = Guid.NewGuid();
                string str      = Path.Combine(tempPath, string.Concat("aquaforest\\pdftoolkit\\", guid.ToString(), "\\", Path.GetFileName(this.filePath)));
                PDFHelper.CheckOutputFolder(Path.GetDirectoryName(str));
                System.IO.File.Copy(this.filePath, str);
                string      str1             = str;
                object      missing          = Type.Missing;
                bool        flag1            = false;
                bool        flag2            = false;
                object      obj              = this.password;
                object      obj1             = this.password;
                object      missing1         = Type.Missing;
                object      obj2             = this.password;
                object      obj3             = this.password;
                object      missing2         = Type.Missing;
                object      missing3         = Type.Missing;
                object      missing4         = Type.Missing;
                object      openAndRepair    = settings.OpenAndRepair;
                object      obj4             = Type.Missing;
                object      missing5         = Type.Missing;
                object      obj5             = Type.Missing;
                Application applicationClass = new ApplicationClass();
                Document    marginLeft       = applicationClass.Open(str1, flag1, flag2, PbSaveOptions.pbDoNotSaveChanges);
                if (settings.MarginLeft > 0f)
                {
                    marginLeft.PageSetup.LeftMargin = settings.MarginLeft;
                }
                if (settings.MarginTop > 0f)
                {
                    marginLeft.PageSetup.TopMargin = settings.MarginTop;
                }
                if (!settings.ConvertHyperLinks)
                {
                    foreach (Page page in marginLeft.Pages)
                    {
                        foreach (Shape shape in page.Shapes)
                        {
                            shape.Hyperlink.Delete();
                        }
                    }
                }
                if ((settings.FromPage <= 0 ? true : settings.ToPage <= 0))
                {
                    bitmapNonEmbeddableFonts = this.BitmapNonEmbeddableFonts;
                    docStructureTags         = this.DocStructureTags;
                    marginLeft.ExportAsFixedFormat(PbFixedFormatType.pbFixedFormatTypePDF, outputFileName, PbFixedFormatIntent.pbIntentPrinting, settings.IncludeDocumentProperty, -1, -1, -1, -1, -1, -1, -1, true, PbPrintStyle.pbPrintStyleDefault, docStructureTags, bitmapNonEmbeddableFonts, settings.PDFA1a, Type.Missing);
                }
                else
                {
                    bool bitmapNonEmbeddableFonts1 = this.BitmapNonEmbeddableFonts;
                    docStructureTags = this.DocStructureTags;
                    bool includeDocumentProperty = settings.IncludeDocumentProperty;
                    bitmapNonEmbeddableFonts = settings.PDFA1a;
                    marginLeft.ExportAsFixedFormat(PbFixedFormatType.pbFixedFormatTypePDF, outputFileName, PbFixedFormatIntent.pbIntentPrinting, includeDocumentProperty, -1, -1, -1, -1, settings.FromPage, settings.ToPage, -1, true, PbPrintStyle.pbPrintStyleDefault, docStructureTags, bitmapNonEmbeddableFonts1, bitmapNonEmbeddableFonts, Type.Missing);
                }
                marginLeft.Close();
                applicationClass.Quit();
                if (System.IO.File.Exists(outputFileName))
                {
                    PDFHelper.DisplayTrialPopupIfNecessary();
                    PDDocument pDDocument = PDDocument.load(new java.io.File(outputFileName));
                    PDFHelper.AddTrialStampIfNecessary(pDDocument, false);
                    pDDocument.save(outputFileName);
                    pDDocument.close();
                }
                PDFHelper.EmptyDirectory(Path.GetDirectoryName(str1));
                flag = true;
            }
            catch (Exception exception1)
            {
                Exception exception = exception1;
                throw new AquaforestOfficeException(exception.Message, exception);
            }
            return(flag);
        }
コード例 #14
0
ファイル: ExcelToPDF.cs プロジェクト: jehan2898/root
        public bool ConvertToPDF(DocumentSettings settings, string outputFileName)
        {
            object ignorePrintAreas;
            bool   flag;

            try
            {
                string tempPath = Path.GetTempPath();
                Guid   guid     = Guid.NewGuid();
                string str      = Path.Combine(tempPath, string.Concat("aquaforest\\pdftoolkit\\", guid.ToString(), "\\", Path.GetFileName(this.filePath)));
                PDFHelper.CheckOutputFolder(Path.GetDirectoryName(str));
                System.IO.File.Copy(this.filePath, str);
                object      missing          = Type.Missing;
                object      obj              = this.password;
                object      obj1             = this.password;
                object      missing1         = Type.Missing;
                object      obj2             = this.password;
                object      obj3             = this.password;
                object      missing2         = Type.Missing;
                object      missing3         = Type.Missing;
                object      missing4         = Type.Missing;
                object      openAndRepair    = settings.OpenAndRepair;
                object      obj4             = Type.Missing;
                object      missing5         = Type.Missing;
                object      obj5             = Type.Missing;
                Application applicationClass = new ApplicationClass();
                Workbook    workbook         = applicationClass.Workbooks.Open(this.filePath, Type.Missing, Type.Missing, Type.Missing, obj, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                foreach (Worksheet worksheet in workbook.Worksheets)
                {
                    if (settings.orientatinIset)
                    {
                        worksheet.PageSetup.Orientation = (XlPageOrientation)settings.PageOrientation;
                    }
                    if (!settings.ConvertHyperLinks)
                    {
                        worksheet.Cells.ClearHyperlinks();
                    }
                    if (settings.paperSizeIset)
                    {
                        worksheet.PageSetup.PaperSize = (XlPaperSize)settings.PaperSize;
                    }
                    if (settings.MarginBottom > 0f)
                    {
                        worksheet.PageSetup.BottomMargin = (double)settings.MarginBottom;
                    }
                    if (settings.MarginLeft > 0f)
                    {
                        worksheet.PageSetup.LeftMargin = (double)settings.MarginLeft;
                    }
                    if (settings.MarginRight > 0f)
                    {
                        worksheet.PageSetup.RightMargin = (double)settings.MarginRight;
                    }
                    if (settings.MarginTop > 0f)
                    {
                        worksheet.PageSetup.TopMargin = (double)settings.MarginTop;
                    }
                    if (this.Zoom <= 0f)
                    {
                        worksheet.PageSetup.Zoom = false;
                        if (this.FitToPagesTall > 0f)
                        {
                            worksheet.PageSetup.FitToPagesTall = this.FitToPagesTall;
                        }
                        if (this.FitToPagesWide > 0f)
                        {
                            worksheet.PageSetup.FitToPagesWide = this.FitToPagesWide;
                        }
                    }
                    else
                    {
                        worksheet.PageSetup.Zoom = this.Zoom;
                    }
                }
                if ((settings.FromPage <= 0 ? true : settings.ToPage <= 0))
                {
                    object obj6 = XlFixedFormatQuality.xlQualityStandard;
                    ignorePrintAreas = this.IgnorePrintAreas;
                    workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, outputFileName, obj6, settings.IncludeDocumentProperty, ignorePrintAreas, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                }
                else
                {
                    object obj7 = XlFixedFormatQuality.xlQualityStandard;
                    ignorePrintAreas = this.IgnorePrintAreas;
                    workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, outputFileName, obj7, settings.IncludeDocumentProperty, ignorePrintAreas, settings.FromPage, settings.ToPage, settings.OpenAfterConverting, Type.Missing);
                }
                workbook.Saved = true;
                workbook.Close(false, Type.Missing, Type.Missing);
                applicationClass.Quit();
                if (System.IO.File.Exists(outputFileName))
                {
                    PDFHelper.DisplayTrialPopupIfNecessary();
                    PDDocument pDDocument = PDDocument.load(new java.io.File(outputFileName));
                    PDFHelper.AddTrialStampIfNecessary(pDDocument, false);
                    pDDocument.save(outputFileName);
                    pDDocument.close();
                }
                PDFHelper.EmptyDirectory(Path.GetDirectoryName(str));
                flag = true;
            }
            catch (Exception exception1)
            {
                Exception exception = exception1;
                throw new AquaforestOfficeException(exception.Message, exception);
            }
            return(flag);
        }
コード例 #15
0
        public PDF2PDFaConverter(string fileName, string output, string password, AquaforestPDFAFlavour PDFAFlavour)
        {
            try
            {
                int pDFAFlavour = (int)PDFAFlavour;
                this.SetFlavour(pDFAFlavour);
                this.PDFAFlavour    = pDFAFlavour;
                this.outPutFileName = output;
                this.inputFileName  = fileName;
                string tempPath = Path.GetTempPath();
                Guid   guid     = Guid.NewGuid();
                this.tempFileName = Path.Combine(tempPath, string.Concat("aquaforest\\pdftoolkit\\", guid.ToString(), "\\", Path.GetFileName(output)));
                string str           = Path.Combine(Path.GetDirectoryName(this.tempFileName), "password.pdf");
                string directoryName = Path.GetDirectoryName(this.tempFileName);
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }
                System.IO.File.Copy(this.inputFileName, str, true);
                PDDocument pDDocument = PDDocument.load(new java.io.File(str));
                if (pDDocument.isEncrypted())
                {
                    pDDocument.setAllSecurityToBeRemoved(true);
                }
                pDDocument.save(this.tempFileName);
                this.doc = new PDDocument();
                switch (this.pdfaversion)
                {
                case 1:
                {
                    if (this.doc.getDocument().getVersion() < 1.4f)
                    {
                        this.doc.getDocument().setVersion(1.4f);
                    }
                    break;
                }

                case 2:
                {
                    if (this.doc.getDocument().getVersion() < 1.7f)
                    {
                        this.doc.getDocument().setVersion(1.7f);
                    }
                    break;
                }

                case 3:
                {
                    if (this.doc.getDocument().getVersion() < 1.7f)
                    {
                        this.doc.getDocument().setVersion(1.7f);
                    }
                    break;
                }
                }
                foreach (PDPage page in pDDocument.getPages())
                {
                    this.doc.addPage(page);
                }
                this.doc.setDocumentInformation(pDDocument.getDocumentInformation());
                this.doc.getDocumentCatalog().setDocumentOutline(pDDocument.getDocumentCatalog().getDocumentOutline());
                this.doc.getDocumentCatalog().setAcroForm(pDDocument.getDocumentCatalog().getAcroForm());
                this.doc.getDocumentCatalog().setLanguage(pDDocument.getDocumentCatalog().getLanguage());
                this.doc.getDocumentCatalog().setMetadata(pDDocument.getDocumentCatalog().getMetadata());
                this.doc.getDocumentCatalog().setPageLabels(pDDocument.getDocumentCatalog().getPageLabels());
                this.doc.getDocumentCatalog().setViewerPreferences(pDDocument.getDocumentCatalog().getViewerPreferences());
                this.doc.getDocumentCatalog().setPageMode(pDDocument.getDocumentCatalog().getPageMode());
                this.doc.getDocumentCatalog().setPageLayout(pDDocument.getDocumentCatalog().getPageLayout());
                this.doc.save(this.tempFileName);
                this.doc.close();
                this.doc = PDDocument.load(new java.io.File(this.tempFileName));
                pDDocument.close();
                pDDocument = null;
                try
                {
                    Assembly executingAssembly      = Assembly.GetExecutingAssembly();
                    Stream   manifestResourceStream = executingAssembly.GetManifestResourceStream("Aquaforest.PDF.sRGB_IEC61966-2-1_black_scaled.icc");
                    using (FileStream fileStream = System.IO.File.Create("sRGB_IEC61966-2-1_black_scaled.icc", (int)manifestResourceStream.Length))
                    {
                        byte[] numArray = new byte[checked (manifestResourceStream.Length)];
                        manifestResourceStream.Read(numArray, 0, (int)numArray.Length);
                        fileStream.Write(numArray, 0, (int)numArray.Length);
                    }
                    manifestResourceStream = executingAssembly.GetManifestResourceStream("Aquaforest.PDF.font.xml");
                    using (FileStream fileStream1 = System.IO.File.Create("font.xml", (int)manifestResourceStream.Length))
                    {
                        byte[] numArray1 = new byte[checked (manifestResourceStream.Length)];
                        manifestResourceStream.Read(numArray1, 0, (int)numArray1.Length);
                        fileStream1.Write(numArray1, 0, (int)numArray1.Length);
                    }
                }
                catch
                {
                }
                this.iccString = "sRGB_IEC61966-2-1_black_scaled.icc";
            }
            catch (InvalidPasswordException invalidPasswordException)
            {
                Console.WriteLine("The Password Provided is Invalid.");
                Environment.Exit(104);
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
                Environment.Exit(104);
            }
        }
コード例 #16
0
ファイル: PowerPointToPDF.cs プロジェクト: jehan2898/root
        public bool ConvertToPDF(DocumentSettings settings, string outputFileName)
        {
            MsoTriState msoTriState;
            bool        flag;

            try
            {
                string tempPath = Path.GetTempPath();
                Guid   guid     = Guid.NewGuid();
                string str      = Path.Combine(tempPath, string.Concat("aquaforest\\pdftoolkit\\", guid.ToString(), "\\", Path.GetFileName(this.filePath)));
                PDFHelper.CheckOutputFolder(Path.GetDirectoryName(str));
                System.IO.File.Copy(this.filePath, str);
                string       str1             = str;
                object       missing          = Type.Missing;
                object       obj              = Type.Missing;
                object       missing1         = Type.Missing;
                object       obj1             = this.password;
                object       obj2             = this.password;
                object       missing2         = Type.Missing;
                object       obj3             = this.password;
                object       obj4             = this.password;
                object       missing3         = Type.Missing;
                object       missing4         = Type.Missing;
                object       missing5         = Type.Missing;
                object       openAndRepair    = settings.OpenAndRepair;
                object       obj5             = Type.Missing;
                object       missing6         = Type.Missing;
                object       obj6             = Type.Missing;
                Application  applicationClass = new ApplicationClass();
                Presentation pageOrientation  = applicationClass.Presentations.Open(str1, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
                msoTriState = (!this.FrameSlides ? MsoTriState.msoFalse : MsoTriState.msoTrue);
                if (settings.orientatinIset)
                {
                    pageOrientation.PageSetup.SlideOrientation = (MsoOrientation)settings.PageOrientation;
                }
                if ((settings.PageHeight <= 0f ? false : settings.PageWidth > 0f))
                {
                    pageOrientation.PageSetup.SlideHeight = settings.PageHeight;
                    pageOrientation.PageSetup.SlideWidth  = settings.PageWidth;
                }
                else if (this.slideSizeIsSet)
                {
                    pageOrientation.PageSetup.SlideSize = (PpSlideSizeType)this.SlideSize;
                }
                if (!settings.ConvertHyperLinks)
                {
                    object obj7 = 1;
                    foreach (Slide slide in pageOrientation.Slides)
                    {
                        while (slide.Hyperlinks.Count > 0)
                        {
                            foreach (Hyperlink hyperlink in slide.Hyperlinks)
                            {
                                hyperlink.Delete();
                            }
                        }
                    }
                }
                AquaforestPDFOptimizeFor    optimizeFor            = settings.OptimizeFor;
                AquaforestPrintHandoutOrder powerPointHandoutOrder = this.PowerPointHandoutOrder;
                bool bitmapNonEmbeddableFonts = this.BitmapNonEmbeddableFonts;
                pageOrientation.ExportAsFixedFormat(outputFileName, PpFixedFormatType.ppFixedFormatTypePDF, (PpFixedFormatIntent)optimizeFor, msoTriState, (PpPrintHandoutOrder)powerPointHandoutOrder, PpPrintOutputType.ppPrintOutputSlides, MsoTriState.msoFalse, null, PpPrintRangeType.ppPrintAll, "", settings.IncludeDocumentProperty, true, true, bitmapNonEmbeddableFonts, settings.PDFA1a, Type.Missing);
                pageOrientation.Close();
                applicationClass.Quit();
                if (System.IO.File.Exists(outputFileName))
                {
                    PDFHelper.DisplayTrialPopupIfNecessary();
                    PDDocument pDDocument = PDDocument.load(new java.io.File(outputFileName));
                    PDFHelper.AddTrialStampIfNecessary(pDDocument, false);
                    pDDocument.save(outputFileName);
                    pDDocument.close();
                }
                PDFHelper.EmptyDirectory(Path.GetDirectoryName(str));
                flag = true;
            }
            catch (Exception exception1)
            {
                Exception exception = exception1;
                throw new AquaforestOfficeException(exception.Message, exception);
            }
            return(flag);
        }
コード例 #17
0
        // Decent example here -- https://github.com/Aiybe/PDFData/blob/master/od-reader/src/main/java/im/abe/pdfdata/AttachmentDataStorage.java

        private void AttachmentZone_Drop(object sender, DragEventArgs e)
        {
            // reset UI
            AttachmentZoneBorder.BorderThickness = new Thickness(1);
            AttachmentZone.Background            = new SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 255, 255));
            deselectAllAttachmentPanels();

            // attach files to PDF
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                // Note that you can have more than one file.
                string[]      files     = (string[])e.Data.GetData(DataFormats.FileDrop);
                List <string> filesList = files.ToList();

                if (pd != null)
                {
                    foreach (string file in filesList)
                    {
                        byte[] fileBytes;
                        try
                        {
                            fileBytes = System.IO.File.ReadAllBytes(file);
                        }
                        catch
                        {
                            // couldn't read file
                            MessageBox.Show("Can't open " + file + " make sure it is not open in another application.", "Can't open file.");
                            continue;
                        }
                        FileStream _filestream        = System.IO.File.Open(file, FileMode.Open);
                        string     nameOfFileToAttach = _filestream.Name;
                        _filestream.Close();

                        PDComplexFileSpecification fs = new PDComplexFileSpecification();
                        fs.setFile(nameOfFileToAttach);

                        ByteArrayInputStream inputStream = new ByteArrayInputStream(fileBytes, 0, fileBytes.Length);
                        //ByteArrayInputStream inputStream = new ByteArrayInputStream(fileBytes);
                        PDEmbeddedFile embeddedFile = new PDEmbeddedFile(pd, inputStream);
                        embeddedFile.setModDate(java.util.Calendar.getInstance());
                        embeddedFile.setSize(fileBytes.Length);
                        fs.setEmbeddedFile(embeddedFile);

                        PDDocumentCatalog        catalog = pd.getDocumentCatalog();
                        PDDocumentNameDictionary names   = catalog.getNames();

                        Map TomsNewMap = new HashMap();
                        if (names != null)
                        {
                            // there are already some attached files
                            PDEmbeddedFilesNameTreeNode embeddedFiles = names.getEmbeddedFiles();
                            Map embeddedFileNames = embeddedFiles.getNames();
                            Dictionary <String, PDComplexFileSpecification> embeddedFileNamesNet = embeddedFileNames.ToDictionary <String, PDComplexFileSpecification>();


                            // Attach all the existing files
                            foreach (KeyValuePair <String, PDComplexFileSpecification> entry in embeddedFileNamesNet)
                            {
                                TomsNewMap.put(entry.Key, entry.Value);
                            }
                        }
                        else
                        {
                            // there are no files already attached -- so create a new name dictionary
                            names = new PDDocumentNameDictionary(catalog);
                        }

                        // Attach the new file
                        TomsNewMap.put(System.IO.Path.GetFileName(nameOfFileToAttach), fs);
                        PDEmbeddedFilesNameTreeNode TomsEmbeddedFiles = new PDEmbeddedFilesNameTreeNode();
                        TomsEmbeddedFiles.setNames(TomsNewMap);
                        names.setEmbeddedFiles(TomsEmbeddedFiles);
                        catalog.setNames(names);

                        pd.save(pathToCurrentPDF);
                        pd.close();
                    }
                }
                else
                {
                    MessageBoxResult result = MessageBox.Show("No PDF file loaded.");
                }
            }

            // reload the PDF
            LoadPDFAndLookForAttachments(pathToCurrentPDF);
        }
コード例 #18
0
ファイル: PDFTextConverter.cs プロジェクト: jehan2898/root
        internal void createPDFFromText(string pdfFile)
        {
            string     str;
            bool       flag;
            PDDocument pDDocument = new PDDocument();

            PDFHelper.DisplayTrialPopupIfNecessary();
            PDFHelper.CheckOutputFolder(Path.GetDirectoryName(pdfFile));
            try
            {
                this.pdfFileName = pdfFile;
                Reader fileReader = new FileReader(this.textFile);
                int    num        = 40;
                if (this.font == null)
                {
                    this.font = PDFType1Font.TIMES_ROMAN;
                }
                float       height = this.font.PDFBoxFont.getBoundingBox().getHeight() / 1000f;
                PDRectangle lETTER = PDRectangle.LETTER;
                if (this.isLandescape)
                {
                    lETTER = new PDRectangle(lETTER.getHeight(), lETTER.getWidth());
                }
                height = height * this.fontSize * 1.05f;
                string[]            strArrays           = System.IO.File.ReadAllLines(this.textFile);
                PDPage              pDPage              = new PDPage(lETTER);
                PDPageContentStream pDPageContentStream = null;
                float    single     = -1f;
                float    width      = pDPage.getMediaBox().getWidth() - (float)(2 * num);
                bool     flag1      = true;
                string[] strArrays1 = strArrays;
                for (int i = 0; i < (int)strArrays1.Length; i++)
                {
                    string str1 = strArrays1[i];
                    flag1 = false;
                    string   str2       = Regex.Replace(str1, "\\t|\\n|\\r", "");
                    string[] strArrays2 = str2.Replace("[\\n\\r]+$", "").Split(new char[] { ' ' });
                    int      num1       = 0;
                    while (num1 < (int)strArrays2.Length)
                    {
                        StringBuilder stringBuilder = new StringBuilder();
                        float         stringWidth   = 0f;
                        bool          flag2         = false;
                        do
                        {
                            string str3 = "";
                            int    num2 = strArrays2[num1].IndexOf('\f');
                            if (num2 != -1)
                            {
                                flag2 = true;
                                str   = strArrays2[num1].Substring(0, num2);
                                if (num2 < strArrays2[num1].Length)
                                {
                                    str3 = strArrays2[num1].Substring(num2 + 1);
                                }
                            }
                            else
                            {
                                str = strArrays2[num1];
                            }
                            if ((str.Length > 0 ? true : !flag2))
                            {
                                stringBuilder.Append(str);
                                stringBuilder.Append(" ");
                            }
                            if ((!flag2 ? false : str3.Length != 0))
                            {
                                strArrays2[num1] = str3;
                            }
                            else
                            {
                                num1++;
                            }
                            if (!flag2)
                            {
                                if (num1 < (int)strArrays2.Length)
                                {
                                    string str4 = strArrays2[num1];
                                    num2 = str4.IndexOf('\f');
                                    if (num2 != -1)
                                    {
                                        str4 = str4.Substring(0, num2);
                                    }
                                    string str5 = string.Concat(stringBuilder.ToString(), " ", str4);
                                    try
                                    {
                                        stringWidth = this.font.PDFBoxFont.getStringWidth(str5) / 1000f * this.fontSize;
                                    }
                                    catch (Exception exception)
                                    {
                                    }
                                }
                                flag = (num1 >= (int)strArrays2.Length ? false : stringWidth < width);
                            }
                            else
                            {
                                break;
                            }
                        }while (flag);
                        if (single < (float)num)
                        {
                            pDPage = new PDPage(lETTER);
                            pDDocument.addPage(pDPage);
                            if (pDPageContentStream != null)
                            {
                                pDPageContentStream.endText();
                                pDPageContentStream.close();
                            }
                            pDPageContentStream = new PDPageContentStream(pDDocument, pDPage);
                            pDPageContentStream.setFont(this.font.PDFBoxFont, this.fontSize);
                            pDPageContentStream.beginText();
                            single = pDPage.getMediaBox().getHeight() - (float)num + height;
                            pDPageContentStream.newLineAtOffset((float)num, single);
                        }
                        if (pDPageContentStream == null)
                        {
                            throw new java.io.IOException("Error:Expected non-null content stream.");
                        }
                        pDPageContentStream.newLineAtOffset(0f, -height);
                        single = single - height;
                        try
                        {
                            pDPageContentStream.showText(stringBuilder.ToString());
                            if (flag2)
                            {
                                pDPage = new PDPage(lETTER);
                                pDDocument.addPage(pDPage);
                                pDPageContentStream.endText();
                                pDPageContentStream.close();
                                pDPageContentStream = new PDPageContentStream(pDDocument, pDPage);
                                pDPageContentStream.setFont(this.font.PDFBoxFont, this.fontSize);
                                pDPageContentStream.beginText();
                                single = pDPage.getMediaBox().getHeight() - (float)num + height;
                                pDPageContentStream.newLineAtOffset((float)num, single);
                            }
                        }
                        catch (Exception exception1)
                        {
                        }
                    }
                }
                if (flag1)
                {
                    pDDocument.addPage(pDPage);
                }
                if (pDPageContentStream != null)
                {
                    pDPageContentStream.endText();
                    pDPageContentStream.close();
                }
                if (PDFHelper.AddStamp)
                {
                    pDDocument = PDFHelper.AddTrialStampIfNecessary(pDDocument);
                }
                try
                {
                    pDDocument.save(pdfFile);
                }
                catch (Exception exception3)
                {
                    Exception exception2 = exception3;
                    throw new PDFToolkitException(exception2.Message, exception2.InnerException);
                }
            }
            catch (Exception exception5)
            {
                Exception exception4 = exception5;
                if (pDDocument != null)
                {
                    pDDocument.close();
                }
                throw exception4;
            }
        }
コード例 #19
0
        private void DrawTable()
        {
            PDPage     pDPage;
            PDDocument pDDocument = new PDDocument();

            pDPage = (this.pageSettings.size != null ? new PDPage(this.pageSettings.size.PDFBoxRectangle) : new PDPage());
            PDRectangle mediaBox  = pDPage.getMediaBox();
            int         num       = this.contents.Count <List <string> >();
            int         num1      = this.contents.ElementAt <List <string> >(0).Count <string>();
            float       width     = mediaBox.getWidth() - (this.pageSettings.marginLeft + this.pageSettings.marginRight);
            float       single    = width / (float)num1;
            float       rowHeight = this.tableSettings.RowHeight;
            float       height    = mediaBox.getHeight() - this.pageSettings.marginTop;
            float       single1   = height - this.pageSettings.marginBottom;
            float       single2   = rowHeight * (float)num;
            int         num2      = num;
            int         num3      = 1;
            int         num4      = 0;

            if (single2 > single1)
            {
                num2    = (int)Math.Floor((double)(single1 / rowHeight));
                num3    = (int)Math.Ceiling((double)num / (double)num2);
                single2 = (float)num2 * rowHeight;
                num4    = num % num2;
            }
            int num5 = 0;

            for (int i = 0; i < num3; i++)
            {
                pDPage = (this.pageSettings.size != null ? new PDPage(this.pageSettings.size.PDFBoxRectangle) : new PDPage());
                pDDocument.addPage(pDPage);
                PDPageContentStream pDPageContentStream = new PDPageContentStream(pDDocument, pDPage);
                if ((i != num3 - 1 ? false : num4 > 0))
                {
                    num2    = num4;
                    single2 = rowHeight * (float)num2;
                }
                float single3 = height;
                for (int j = 0; j <= num2; j++)
                {
                    pDPageContentStream.drawLine(this.pageSettings.marginLeft, single3, this.pageSettings.marginLeft + width, single3);
                    single3 = single3 - rowHeight;
                }
                float single4 = this.pageSettings.marginLeft;
                for (int k = 0; k <= num1; k++)
                {
                    pDPageContentStream.drawLine(single4, height, single4, height - single2);
                    single4 = single4 + single;
                }
                pDPageContentStream.setFont(this.pageSettings.Font.PDFBoxFont, this.pageSettings.FontSize);
                float cellMargin = this.pageSettings.marginLeft + this.tableSettings.CellMargin;
                float single5    = height - 15f;
                for (int l = 0; l < num2; l++)
                {
                    foreach (string item in this.contents[num5])
                    {
                        pDPageContentStream.beginText();
                        pDPageContentStream.newLineAtOffset(cellMargin, single5);
                        pDPageContentStream.showText(item);
                        pDPageContentStream.endText();
                        cellMargin = cellMargin + single;
                    }
                    single5    = single5 - rowHeight;
                    cellMargin = this.pageSettings.marginLeft + this.tableSettings.CellMargin;
                    num5++;
                }
                pDPageContentStream.close();
            }
            pDDocument = PDFHelper.AddTrialStampIfNecessary(pDDocument);
            pDDocument.save(this.outputPDF);
        }