Пример #1
12
 private void button2_Click(object sender, EventArgs e)
 {
     string exeDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + Path.DirectorySeparatorChar;
     string dataDir = new Uri(new Uri(exeDir), @"../../Data/").LocalPath;
     Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(dataDir + "//InputFile.pdf");
     for (int pageCount = 1; pageCount <= pdfDocument.Pages.Count; pageCount++)
     {
         using (FileStream imageStream = new FileStream("image" + pageCount + ".png", FileMode.Create))
         {
             Resolution resolution = new Resolution(300);
             PngDevice pngDevice = new PngDevice(resolution);
             pngDevice.Process(pdfDocument.Pages[pageCount], imageStream);
             imageStream.Close();
             MessageBox.Show("png file created in \\bin\\Debug");
         }
     }
 }
        public static int GetPDFPageCount(string faxPath)
        {
            InvokeAposePdfLicense();            

            Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(faxPath);
            return pdfDocument.Pages.Count;
        }
Пример #3
1
 protected void publish_import_upload_OnFileUploaded(object sender, FileUploadedEventArgs e)
 {
     var id = CurrentResource.Id;
     var file = e.File;
     var tempId = HomoryContext.Value.GetId();
     var suffix = file.GetExtension().Replace(".", "").ToLower();
     var path = string.Format("../Common/资源/{0}/{1}/{2}.{3}", CurrentUser.Id.ToString().ToUpper(), ResourceType.ToString(),
         tempId.ToString().ToUpper(), ResourceType == ResourceType.视频 ? suffix == "flv" ? suffix : "mp4" : "pdf");
     var pathX = Server.MapPath(path);
     var source = string.Format("../Common/资源/{0}/{1}/{2}.{3}", CurrentUser.Id.ToString().ToUpper(), ResourceType.ToString(),
         tempId.ToString().ToUpper(), suffix);
     var sourceX = Server.MapPath(source);
     var cpic = path.Replace(".pdf", ".jpg").Replace(".flv", ".jpg").Replace(".mp4", ".jpg");
     var cpicX = pathX.Replace(".pdf", ".jpg").Replace(".flv", ".jpg").Replace(".mp4", ".jpg");
     var res = HomoryContext.Value.Resource.Single(o => o.Id == id);
     file.SaveAs(sourceX, true);
     switch (suffix)
     {
         case "doc":
         case "docx":
         case "txt":
         case "rtf":
             var docW = new Aspose.Words.Document(sourceX);
             docW.Save(pathX, Aspose.Words.SaveFormat.Pdf);
             docW.Save(cpicX, Aspose.Words.SaveFormat.Jpeg);
             res.Image = cpic;
             res.FileType = ResourceFileType.Word;
             res.Thumbnail = ((int)ResourceFileType.Word).ToString();
             break;
         case "ppt":
         case "pptx":
             var docP = new Aspose.Slides.Presentation(sourceX);
             docP.Save(pathX, Aspose.Slides.Export.SaveFormat.Pdf);
             var tcdocp = new Aspose.Pdf.Document(pathX);
             using (var imageStream = new FileStream(cpicX, FileMode.Create))
             {
                 var resolution = new Resolution(300);
                 var jpegDevice = new JpegDevice(resolution, 100);
                 jpegDevice.Process(tcdocp.Pages[1], imageStream);
                 imageStream.Close();
             }
             res.Image = cpic;
             res.FileType = ResourceFileType.Powerpoint;
             res.Thumbnail = ((int)ResourceFileType.Powerpoint).ToString();
             break;
         case "xls":
         case "xlsx":
             var docE = new Aspose.Cells.Workbook(sourceX);
             docE.Save(pathX, Aspose.Cells.SaveFormat.Pdf);
             var tcdoce = new Aspose.Pdf.Document(pathX);
             using (var imageStream = new FileStream(cpicX, FileMode.Create))
             {
                 var resolution = new Resolution(300);
                 var jpegDevice = new JpegDevice(resolution, 100);
                 jpegDevice.Process(tcdoce.Pages[1], imageStream);
                 imageStream.Close();
             }
             res.Image = cpic;
             res.FileType = ResourceFileType.Excel;
             res.Thumbnail = ((int)ResourceFileType.Excel).ToString();
             break;
         case "pdf":
             var tcdoc = new Aspose.Pdf.Document(pathX);
             using (var imageStream = new FileStream(cpicX, FileMode.Create))
             {
                 var resolution = new Resolution(300);
                 var jpegDevice = new JpegDevice(resolution, 100);
                 jpegDevice.Process(tcdoc.Pages[1], imageStream);
                 imageStream.Close();
             }
             res.Image = cpic;
             res.FileType = ResourceFileType.Pdf;
             res.Thumbnail = ((int)ResourceFileType.Pdf).ToString();
             break;
         case "avi":
         case "mpg":
         case "mpeg":
         case "flv":
         case "mp4":
         case "rm":
         case "rmvb":
         case "wmv":
             NReco.VideoConverter.FFMpegConverter c = new NReco.VideoConverter.FFMpegConverter();
             c.GetVideoThumbnail(sourceX, cpicX, 2F);
             //if (!sourceX.EndsWith("flv", StringComparison.OrdinalIgnoreCase))
             //{
             //    c.ConvertMedia(sourceX, pathX, NReco.VideoConverter.Format.flv);
             //}
             res.Image = cpic;
             res.FileType = ResourceFileType.Media;
             res.Thumbnail = ((int)ResourceFileType.Media).ToString();
             break;
     }
     res.SourceName = file.GetName();
     res.Title = file.GetNameWithoutExtension();
     res.Source = source;
     res.Preview = path;
     res.Converted = true;
     HomoryContext.Value.SaveChanges();
 }
        private string CreateDocumentBasedOnPageCount(ScannedDocument barCodeText)
        {
            Aspose.Pdf.Document pdfDocument1 = new Aspose.Pdf.Document(barCodeText.FullPath);
            Aspose.Pdf.Document pdfDocument2 = new Aspose.Pdf.Document();
            string returnDocumentName = string.Empty;

            for (int i = 1; i <= barCodeText.PageCount; i++)
            {
                pdfDocument2.Pages.Add(pdfDocument1.Pages[i]);
            }

            returnDocumentName = ConfigurationValues.PathToWorkingFolder + Utility.GetFileNameFromDateTimeString() + ".pdf";
            pdfDocument2.Save(returnDocumentName);
            pdfDocument1.Dispose();

            Aspose.Pdf.Document pdfDocument3 = new Aspose.Pdf.Document(barCodeText.FullPath);

            for (int i = 1; i <= barCodeText.PageCount; i++)
            {
                pdfDocument3.Pages.Delete(1);
            }

            File.Delete(barCodeText.FullPath);
            pdfDocument3.Save(barCodeText.FullPath);
            pdfDocument3.Dispose();
            return returnDocumentName;
        }
        public static void Run()
        {
            //ExStart: AddAndSearchHiddenText
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();

            //Create document with hidden text
            Aspose.Pdf.Document doc = new Aspose.Pdf.Document();
            Page         page       = doc.Pages.Add();
            TextFragment frag1      = new TextFragment("This is common text.");
            TextFragment frag2      = new TextFragment("This is invisible text.");

            //Set text property - invisible
            frag2.TextState.Invisible = true;

            page.Paragraphs.Add(frag1);
            page.Paragraphs.Add(frag2);
            doc.Save(dataDir + "39400_out.pdf");
            doc.Dispose();

            //Search text in the document
            doc = new Aspose.Pdf.Document(dataDir + "39400_out.pdf");
            TextFragmentAbsorber absorber = new TextFragmentAbsorber();

            absorber.Visit(doc.Pages[1]);

            foreach (TextFragment fragment in absorber.TextFragments)
            {
                //Do something with fragments
                Console.WriteLine("Text '{0}' on pos {1} invisibility: {2} ",
                                  fragment.Text, fragment.Position.ToString(), fragment.TextState.Invisible);
            }
            doc.Dispose();
            //ExEnd: AddAndSearchHiddenText
        }
Пример #6
0
        private static string GetPdfText_Aspose(Aspose.Pdf.Document pdf)
        {
            System.Text.StringBuilder builder = new System.Text.StringBuilder();
            // String to hold extracted text
            string extractedText = "";

            foreach (Aspose.Pdf.Page pdfPage in pdf.Pages)
            {
                using (System.IO.MemoryStream textStream = new System.IO.MemoryStream())
                {
                    // Create text device
                    Aspose.Pdf.Devices.TextDevice textDevice = new Aspose.Pdf.Devices.TextDevice();

                    // Set text extraction options - set text extraction mode (Raw or Pure)
                    Aspose.Pdf.Text.TextOptions.TextExtractionOptions textExtOptions = new
                                                                                       Aspose.Pdf.Text.TextOptions.TextExtractionOptions(Aspose.Pdf.Text.TextOptions.TextExtractionOptions.TextFormattingMode.Pure);
                    textDevice.ExtractionOptions = textExtOptions;

                    // Convert a particular page and save text to the stream
                    textDevice.Process(pdfPage, textStream);
                    // Convert a particular page and save text to the stream
                    //textDevice.Process(pdf.Pages[1], textStream);

                    // Close memory stream
                    textStream.Close();

                    // Get text from memory stream
                    extractedText = Encoding.Unicode.GetString(textStream.ToArray());
                    //extractedText = encoding.GetString(textStream.ToArray());
                }
                builder.Append(extractedText);
            }
            return(builder.ToString());
        }
Пример #7
0
        ///<Summary>
        /// ConvertPdfToEmf method to convert PDF to Emf
        ///</Summary>
        public Response ConvertPdfToEmf(string fileName, string folderName)
        {
            return(ProcessTask(fileName, folderName, ".emf", true, "", true, delegate(string inFilePath, string outPath, string zipOutFolder)
            {
                Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(inFilePath);

                string outfileName = Path.GetFileNameWithoutExtension(fileName) + "_{0}";
                int totalPages = pdfDocument.Pages.Count;

                for (int pageCount = 1; pageCount <= totalPages; pageCount++)
                {
                    if (totalPages > 1)
                    {
                        outPath = zipOutFolder + "/" + outfileName;
                        outPath = string.Format(outPath, pageCount);
                    }
                    else
                    {
                        outPath = zipOutFolder + "/" + Path.GetFileNameWithoutExtension(fileName);
                    }

                    Resolution resolution = new Resolution(300);
                    var emfDevice = new EmfDevice(resolution);
                    emfDevice.Process(pdfDocument.Pages[pageCount], outPath + ".emf");
                }
            }));
        }
Пример #8
0
        private void button1_Click(object sender, EventArgs e)
        {
            var imageWidth    = 77;
            var imageHeight   = 109;
            var resolution    = new Aspose.Pdf.Devices.Resolution(300);
            var imageDevice   = new Aspose.Pdf.Devices.PngDevice(imageWidth, imageHeight, resolution);
            var path          = Path.GetDirectoryName(Application.ExecutablePath).Replace("bin\\Debug", string.Empty);
            var testFile      = path + @"TestImages\Superheros.pdf";
            var imageLocation = path + "GeneratedImages\\Superheros.png";
            var dummypath     = path + "DummyFolder\\Superheroes.pdf";
            var pdfDocument   = new Aspose.Pdf.Document(testFile);

            imageDevice.RenderingOptions.SystemFontsNativeRendering = true;


            //Having this line results in  "GeneratedImages\\Superheros.png"; being empty. Not having it makes the said png have the text from the source-pdf
            pdfDocument.Save(dummypath);

            if (imageDevice != null)
            {
                using (var imageStream = new FileStream(imageLocation, FileMode.OpenOrCreate))
                {
                    imageDevice.Process(pdfDocument.Pages[1], imageStream);
                    imageStream.Close();
                }
            }
        }
Пример #9
0
        private string PDFSaveAsHTML(string thePath)
        {
            Aspose.Pdf.Document document = new Aspose.Pdf.Document(thePath);
            string con     = string.Empty;
            var    device  = new Aspose.Pdf.Devices.JpegDevice();
            int    quality = 80;

            //默认质量为100,设置质量的好坏与处理速度不成正比,甚至是设置的质量越低反而花的时间越长,怀疑处理过程是先生成高质量的再压缩
            device = new Aspose.Pdf.Devices.JpegDevice(quality);
            //遍历每一页转为jpg
            for (var i = 1; i <= document.Pages.Count; i++)
            {
                string     filePathOutPut = Path.Combine(Server.MapPath("/uploadfiles/import/" + fileName + "/"), string.Format("img_{0}.jpg", i));
                FileStream fs             = new FileStream(filePathOutPut, FileMode.OpenOrCreate);
                try
                {
                    device.Process(document.Pages[i], fs);
                    fs.Close();
                }
                catch (Exception ex)
                {
                    fs.Close();
                    File.Delete(filePathOutPut);
                }

                con += "<br><img src='/uploadfiles/import/" + fileName + "/img_" + i + ".jpg'>";
            }

            return(con);
        }
Пример #10
0
    /// <summary>
    /// 将Word文档转化为图片
    /// </summary>
    /// <param name="wordpath">需要转换的word文档的全路径</param>
    public void Word_Convert2Image(string wordpath)
    {
        //第一步:将Word文档转化为Pdf文档(中间过程)
        Aspose.Words.Document doc = new Aspose.Words.Document(wordpath);
        //生成的pdf的路径
        string Pdfpath = Server.MapPath("images") + "Word2Pdf.pdf";

        doc.Save(Pdfpath, Aspose.Words.SaveFormat.Pdf);  //生成中间文档pdf

        //第二部:开始把第一步中转化的pdf文档转化为图片
        int i = 1;

        Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(Pdfpath);
        while (i <= pdfDocument.Pages.Count)
        {
            if (!string.IsNullOrEmpty(Pdfpath))
            {
                GetImage(Pdfpath, i);
                GC.Collect();  //回收内存
            }
            i++;
        }
        //图片转化完成之后,删除中间过程产生的pdf文档
        if (File.Exists(Pdfpath))
        {
            File.Delete(Pdfpath);
        }
    }
        public void IgnoreNoscriptElements(bool ignoreNoscriptElements)
        {
            //ExStart
            //ExFor:HtmlLoadOptions.IgnoreNoscriptElements
            //ExSummary:Shows how to ignore <noscript> HTML elements.
            const string html = @"
                <html>
                  <head>
                    <title>NOSCRIPT</title>
                      <meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8"">
                      <script type=""text/javascript"">
                        alert(""Hello, world!"");
                      </script>
                  </head>
                <body>
                  <noscript><p>Your browser does not support JavaScript!</p></noscript>
                </body>
                </html>";

            HtmlLoadOptions htmlLoadOptions = new HtmlLoadOptions();

            htmlLoadOptions.IgnoreNoscriptElements = ignoreNoscriptElements;

            Document doc = new Document(new MemoryStream(Encoding.UTF8.GetBytes(html)), htmlLoadOptions);

            doc.Save(ArtifactsDir + "HtmlLoadOptions.IgnoreNoscriptElements.pdf");
            //ExEnd

            Aspose.Pdf.Document pdfDoc       = new Aspose.Pdf.Document(ArtifactsDir + "HtmlLoadOptions.IgnoreNoscriptElements.pdf");
            TextAbsorber        textAbsorber = new TextAbsorber();

            textAbsorber.Visit(pdfDoc);

            Assert.AreEqual(ignoreNoscriptElements ? "" : "Your browser does not support JavaScript!", textAbsorber.Text);
        }
Пример #12
0
        public static string GetPdfText_Aspose(byte[] buffer)
        {
            var ms = new System.IO.MemoryStream(buffer);

            Aspose.Pdf.Document pdf = new Aspose.Pdf.Document(ms);
            return(GetPdfText_Aspose(pdf));
        }
Пример #13
0
        public static void Pdf2Html(string filename, string targetPath = null)
        {
            if (!File.Exists(filename))
            {
                throw new FileNotFoundException();
            }

            if (!IsPdfDocument(filename))
            {
                throw new InvalidOperationException("此函数仅支持转换“.pdf”格式的文件");
            }

            if (!targetPath.IsNullOrEmpty())
            {
                if (!Directory.Exists(targetPath))
                {
                    Directory.CreateDirectory(targetPath);
                }
            }
            else
            {
                targetPath = Path.GetDirectoryName(filename);
            }

            var htmlFilename = Path.Combine(targetPath, Path.GetFileNameWithoutExtension(filename) + ".html");

            var doc = new Aspose.Pdf.Document(filename);

            doc.Save(htmlFilename, Aspose.Pdf.SaveFormat.Html);
            doc.Save(htmlFilename, new Aspose.Pdf.HtmlSaveOptions {
                DocumentType = Aspose.Pdf.HtmlDocumentType.Html5
            });
        }
        public static void Run()
        {
            // ExStart:1
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_StampsWatermarks();

            // Instantiate Document instance by calling empty constructor
            Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document();
            // Create a page in the pdf document
            Aspose.Pdf.Page page = pdfDocument.Pages.Add();

            // Create a Header Section of the PDF file
            Aspose.Pdf.HeaderFooter header = new Aspose.Pdf.HeaderFooter();
            // Set the Odd Header for the PDF file
            page.Header = header;
            // Set the top margin for the header section
            header.Margin.Top = 20;

            // Instantiate a table object
            Aspose.Pdf.Table tab1 = new Aspose.Pdf.Table();
            // Add the table in paragraphs collection of the desired section
            header.Paragraphs.Add(tab1);
            // Set default cell border using BorderInfo object
            tab1.DefaultCellBorder = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, 0.1F);
            // Set with column widths of the table
            tab1.ColumnWidths = "60 300";

            Aspose.Pdf.Image img = new Aspose.Pdf.Image();
            img.File = dataDir + "aspose-logo.jpg";

            // Create rows in the table and then cells in the rows
            Aspose.Pdf.Row row1 = tab1.Rows.Add();

            row1.Cells.Add("Table in Header Section");
            row1.BackgroundColor = Color.Gray;
            // Set the row span value for first row as 2
            tab1.Rows[0].Cells[0].ColSpan = 2;
            tab1.Rows[0].Cells[0].DefaultCellTextState.ForegroundColor = Color.Cyan;
            tab1.Rows[0].Cells[0].DefaultCellTextState.Font            = FontRepository.FindFont("Helvetica");
            // Create rows in the table and then cells in the rows
            Aspose.Pdf.Row row2 = tab1.Rows.Add();
            // Set the background color for Row2
            row2.BackgroundColor = Color.White;
            // Add the cell which holds the image
            Aspose.Pdf.Cell cell2 = row2.Cells.Add();
            // Set the image width to 60
            img.FixWidth = 60;

            // Add the image to the table cell
            cell2.Paragraphs.Add(img);
            row2.Cells.Add("Logo is looking fine !");
            row2.Cells[1].DefaultCellTextState.Font = FontRepository.FindFont("Helvetica");
            // Set the vertical allignment of the text as center alligned
            row2.Cells[1].VerticalAlignment = Aspose.Pdf.VerticalAlignment.Center;
            row2.Cells[1].Alignment         = Aspose.Pdf.HorizontalAlignment.Center;

            // Save the Pdf file
            pdfDocument.Save(dataDir + "TableInHeaderFooterSection_out.pdf");
            // ExEnd:1
        }
        public HttpResponseMessage Page(RequestData request)
        {
            Opts.AppName    = "Viewer";
            Opts.FileName   = request.fileName;
            Opts.FolderName = request.folderName;
            Opts.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            //var filename = AppSettings.OutputDirectory + Opts.FolderName + "/" + Opts.FileName;
            //Path.GetFileNameWithoutExtension(Opts.FileName) + "_links.pdf"; // This file was prepared by PrepareInternalLinks method
            try
            {
                if (Opts.FolderName.Contains(".."))
                {
                    throw new Exception("Break-in attempt");
                }

                var doc  = new Document(Opts.WorkingFileName);
                var page = PreparePageView(doc, request.pageNumber);
                return(Request.CreateResponse(HttpStatusCode.OK, page));
            }
            catch (Exception ex)
            {
                return(ExceptionResponse(ex));
            }
        }
Пример #16
0
        public void LoadPdf()
        {
            //ExStart
            //ExFor:Document.#ctor(String)
            //ExSummary:Shows how to load a PDF.
            Aspose.Words.Document doc     = new Aspose.Words.Document();
            DocumentBuilder       builder = new DocumentBuilder(doc);

            builder.Write("Hello world!");

            doc.Save(ArtifactsDir + "PDF2Word.LoadPdf.pdf");

            // Below are two ways of loading PDF documents using Aspose products.
            // 1 -  Load as an Aspose.Words document:
            Aspose.Words.Document asposeWordsDoc = new Aspose.Words.Document(ArtifactsDir + "PDF2Word.LoadPdf.pdf");

            Assert.AreEqual("Hello world!", asposeWordsDoc.GetText().Trim());

            // 2 -  Load as an Aspose.Pdf document:
            Aspose.Pdf.Document asposePdfDoc = new Aspose.Pdf.Document(ArtifactsDir + "PDF2Word.LoadPdf.pdf");

            TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber();

            asposePdfDoc.Pages.Accept(textFragmentAbsorber);

            Assert.AreEqual("Hello world!", textFragmentAbsorber.Text.Trim());
            //ExEnd
        }
Пример #17
0
        static void Main(string[] args)
        {
            string dir      = @"E:\Convert\pdf\";
            int    r        = 50;
            string fileName = "t2222";
            string pdfFile  = dir + fileName + ".pdf";
            string imgFile  = dir + fileName + "_asposePDF_" + r.ToString() + ".jpg";

            //ConsoleTest3.ModifyInMemory.ActivateMemoryPatching();
            Aspose.Pdf.Document document = new Aspose.Pdf.Document(pdfFile);
            var device = new Aspose.Pdf.Devices.JpegDevice(r);

            //遍历每一页转为jpg
            for (var i = 1; i <= document.Pages.Count; i++)
            {
                string     filePathOutPut = System.IO.Path.Combine(dir, string.Format("{0}.jpg", i));
                FileStream fs             = new FileStream(imgFile, FileMode.OpenOrCreate);
                try
                {
                    device.Process(document.Pages[1], fs);
                    fs.Close();
                }
                catch (Exception ex)
                {
                    fs.Close();
                    File.Delete(filePathOutPut);
                }
                break;
            }
        }
Пример #18
0
        public static void PDFThumbImage(string pdfInputPath, string imageOutputPath, string imageName)
        {
            if (!File.Exists(pdfInputPath))
            {
                throw new FileNotFoundException();
            }
            if (!Directory.Exists(imageOutputPath))
            {
                Directory.CreateDirectory(imageOutputPath);
            }

            //Open document

            Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(pdfInputPath);
            int Count = pdfDocument.Pages.Count;

            Count = 1;
            for (int pageCount = 1; pageCount <= Count; pageCount++)//1
            {
                string _path = Path.Combine(imageOutputPath, imageName) + "_" + pageCount + ".jpg";

                using (FileStream imageStream = new FileStream(_path, FileMode.Create))
                {
                    //Create Resolution object
                    Aspose.Pdf.Devices.Resolution rs         = new Aspose.Pdf.Devices.Resolution(300);
                    Aspose.Pdf.Devices.JpegDevice jpegDevice = new Aspose.Pdf.Devices.JpegDevice(200, 150, rs, 100);
                    //Convert a particular page and save the image to stream
                    jpegDevice.Process(pdfDocument.Pages[pageCount], imageStream);
                    //Close stream
                    imageStream.Close();
                }
            }
        }
        public HttpResponseMessage Print(RequestData request)
        {
            Opts.AppName    = "Viewer";
            Opts.FileName   = request.fileName;
            Opts.FolderName = request.folderName;
            Opts.MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;

            try
            {
                if (Opts.FolderName.Contains(".."))
                {
                    throw new Exception("Break-in attempt");
                }

                var doc = new Document(Opts.WorkingFileName);
                var lst = new PageView[doc.Pages.Count];
                for (int i = 0; i < doc.Pages.Count; i++)
                {
                    lst[i] = PreparePageView(doc, i + 1);
                }
                return(Request.CreateResponse(HttpStatusCode.OK, lst));
            }
            catch (Exception ex)
            {
                return(ExceptionResponse(ex));
            }
        }
Пример #20
0
        protected void Converter(string path, string extension)
        {
            switch (extension)
            {
            case ".pdf":
                Aspose.Pdf.Document       pdfDoc = new Aspose.Pdf.Document(ExtensionClass.AttchmentFolder + "\\" + path);
                Aspose.Pdf.DocSaveOptions opts   = new Aspose.Pdf.DocSaveOptions();
                opts.Format = Aspose.Pdf.DocSaveOptions.DocFormat.Doc;
                opts.Mode   = Aspose.Pdf.DocSaveOptions.RecognitionMode.Flow;
                pdfDoc.Save(ApplicationSettings.Outputurl + "/output.doc", opts);
                // Load in the document
                Document docpdf = new Document(ApplicationSettings.Outputurl + "/output.doc");

                docpdf.Range.Replace("\t", "\n");
                docpdf.Save(ApplicationSettings.Outputurl + "/output.txt");
                break;

            case ".doc":
            case ".docx":
            case ".txt":
            case ".rtf":
            {
                // Load in the document
                Document doc = new Document(path);
                doc.Save(ApplicationSettings.Outputurl + "/output.doc");
                break;
            }
            }
            ConvertDocument(ApplicationSettings.Outputurl + "/output.doc");
        }
Пример #21
0
        private static void ReplaceTextExampleSimple()
        {
            var eventDate          = new DateTime(2018, 6, 1);
            var listOfreplacements = new List <StringPair>
            {
                new StringPair("<FirstName>", "Sherlock"),
                new StringPair("<LastName>", "Holmes"),
                new StringPair("<ShortDate>", eventDate.ToString("MMM dd, yyyy")),
                new StringPair("<ShortTime>", "6:00PM"),
                new StringPair("<ImportantDate1>", eventDate.AddDays(-1).ToString("MMM dd, yyyy")),
                new StringPair("<ImportantDate3>", eventDate.AddDays(1).ToString("MMM dd, yyyy")),
                new StringPair("<ImportantDate4>", eventDate.AddDays(7).ToString("MMM dd, yyyy"))
            };
            var pdfDocument      = new Aspose.Pdf.Document(@".\Data\invitation.pdf");
            var pdfContentEditor = new Aspose.Pdf.Facades.PdfContentEditor();

            pdfContentEditor.BindPdf(pdfDocument);
            pdfContentEditor.TextReplaceOptions.ReplaceScope = TextReplaceOptions.Scope.REPLACE_FIRST;

            foreach (var replacement in listOfreplacements)
            {
                pdfContentEditor.ReplaceText(replacement.oldValue, replacement.newValue);
            }

            pdfContentEditor.TextReplaceOptions.ReplaceScope = TextReplaceOptions.Scope.REPLACE_ALL;
            pdfContentEditor.ReplaceText("<ProgramTitle>", "Violin Contest");
            pdfContentEditor.ReplaceText("<ImportantDate2>", eventDate.ToString("MMMM dd, yyyy"));

            pdfContentEditor.Save(@".\Data\invitation-0.pdf");
        }
Пример #22
0
        public static void Run()
        {
            // ExStart:1
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_StampsWatermarks();

            Aspose.Pdf.Document doc = new Aspose.Pdf.Document();
            // Create a page in the document object
            Aspose.Pdf.Page page = doc.Pages.Add();

            // Create Header Section of the document
            Aspose.Pdf.HeaderFooter header = new Aspose.Pdf.HeaderFooter();
            // Set the header for the PDF file
            page.Header = header;
            // Create an image object in the page
            Aspose.Pdf.Image image1 = new Aspose.Pdf.Image();
            // Set the path of image file
            image1.File = dataDir + "aspose-logo.jpg";
            // Add image to Header page of the Pdf file
            header.Paragraphs.Add(image1);

            // Create a Footer Section of the document
            Aspose.Pdf.HeaderFooter footer = new Aspose.Pdf.HeaderFooter();
            // Set the footer of the PDF file
            page.Footer = footer;
            // Create a Text object
            Aspose.Pdf.Text.TextFragment txt = new Aspose.Pdf.Text.TextFragment("Page: ($p of $P ) ");
            // Add text to Header section of the Pdf file
            footer.Paragraphs.Add(txt);
            // Save the Pdf file
            doc.Save(dataDir + "ImageAndPageNumberInHeaderFooter_out.pdf");
            // ExEnd:1
        }
Пример #23
0
        public void ConvertToImage(string filePath, int resolution)
        {
            Aspose.Pdf.Document doc = new Aspose.Pdf.Document(filePath);
            string imageName        = Path.GetFileNameWithoutExtension(filePath);

            for (int i = 1; i <= doc.Pages.Count; i++)
            {
                int    pageNum = i;
                string imgPath = string.Format("{0}_{1}.Jpeg", Path.Combine(Path.GetDirectoryName(filePath), imageName), i.ToString("000"));
                if (File.Exists(imgPath))
                {
                    InvokeCallBack(pageNum, imgPath);
                    continue;
                }

                using (MemoryStream stream = new MemoryStream())
                {
                    Aspose.Pdf.Devices.Resolution reso       = new Aspose.Pdf.Devices.Resolution(resolution);
                    Aspose.Pdf.Devices.JpegDevice jpegDevice = new Aspose.Pdf.Devices.JpegDevice(reso, 100);
                    jpegDevice.Process(doc.Pages[i], stream);
                    using (Image image = Image.FromStream(stream))
                    {
                        new Bitmap(image).Save(imgPath, ImageFormat.Jpeg);
                    }
                }
                InvokeCallBack(pageNum, imgPath);
            }

            Task.WaitAll(TaskList.ToArray());
        }
Пример #24
0
        private void LoadImageOnPdfFile_3()
        {
            //create filename of pdf_file_tosave
            var pdf_file_tosave = @"d:\1.pdf";

            //new pdf doc
            var pdfDoc = new Aspose.Pdf.Document();

            //editing
            pdfDoc.SetTitle("hello!");
            var pdfPage = pdfDoc.Pages.Add();

            //var te1 = new Aspose.Pdf.Text.TextSegment();
            pdfPage.AddImage(@"F:\MyDesktop\en-HandWritting\e.jpg", new Aspose.Pdf.Rectangle(0, 0, 500, 500));

            //save
            try
            {
                pdfDoc.Save(pdf_file_tosave, Aspose.Pdf.SaveFormat.Pdf);
                MessageBox.Show("Save Successfully!");
                pdfDoc.Dispose();
                Process.Start(pdf_file_tosave);
            }
            catch
            {
                MessageBox.Show("Faild to Save!");
            }
        }
Пример #25
0
        public static bool ConvertPreview(VMCloud.Models.File file, string savePath)
        {
            string ext = GetFileExtensioName(file.name);

            switch (ext)
            {
            case "doc":
            case "docx":
                Document document = new Document(file.path);
                document.Save(savePath, Aspose.Words.SaveFormat.Pdf);
                break;

            case "pdf":
                Aspose.Pdf.Document pdf = new Aspose.Pdf.Document(file.path);
                pdf.Save(savePath, Aspose.Pdf.SaveFormat.Pdf);
                break;

            case "ppt":
            case "pptx":
                Presentation ppt = new Presentation(file.path);
                ppt.Save(savePath, Aspose.Slides.Export.SaveFormat.Pdf);
                break;

            case "xls":
            case "xlsx":
                Workbook book = new Workbook(file.path);
                book.Save(savePath, Aspose.Cells.SaveFormat.Pdf);
                break;

            default:
                return(false);
            }
            return(true);
        }
Пример #26
0
        /// <summary>
        /// PPT文档转图片
        /// </summary>
        /// <param name="pptFileName"></param>
        /// <param name="outPutFilePath"></param>
        public void PPTToImg(string pptFileName, string outPutFilePath)
        {
            Presentation ppt = new Presentation(pptFileName);
            Stream       st  = new MemoryStream();

            ppt.Save(st, SaveFormat.Pdf);
            Aspose.Pdf.Document document = new Aspose.Pdf.Document(st);
            var device = new Aspose.Pdf.Devices.JpegDevice();

            //默认质量为100,设置质量的好坏与处理速度不成正比,甚至是设置的质量越低反而花的时间越长,怀疑处理过程是先生成高质量的再压缩
            device = new Aspose.Pdf.Devices.JpegDevice(100);
            //遍历每一页转为jpg
            for (var i = 1; i <= document.Pages.Count; i++)
            {
                string     savepath = outPutFilePath + "\\" + string.Format("{0}.jpg", i);
                FileStream fs       = new FileStream(savepath, FileMode.OpenOrCreate);
                try
                {
                    device.Process(document.Pages[i], fs);
                    fs.Close();
                }
                catch (Exception ex)
                {
                    fs.Close();
                    LogControl.LogInfo(lastCheckId.ToString() + "PPT文档转图片执行失败:" + ex.Message.ToString());
                }
            }
        }
Пример #27
0
 /// <summary>
 /// 将pdf文档转换为jpg图片
 /// </summary>
 /// <param name="filePath">选择文件的路径</param>
 /// <param name="fileName">选择文件的文件名称</param>
 private void pdfConverToImage(string filePath, string fileName)
 {
     try
     {
         Aspose.Pdf.Document           document   = new Aspose.Pdf.Document(filePath);
         Aspose.Pdf.Devices.Resolution resolution = new Aspose.Pdf.Devices.Resolution(300);
         Aspose.Pdf.Devices.JpegDevice jpegDevice = new Aspose.Pdf.Devices.JpegDevice(resolution, 100);
         for (int i = 1; i <= document.Pages.Count; i++)
         {
             FileStream fileStream = new FileStream(fileName.Split('.')[0] + i + ".jpg", FileMode.OpenOrCreate);
             jpegDevice.Process(document.Pages[i], fileStream);
             fileStream.Close();
         }
         lblConver.Visible = false;
         DialogResult dialogResult = MessageBox.Show("转换成功,是否打开转换图片文件夹", "转换结果", MessageBoxButtons.OKCancel);
         if (dialogResult == DialogResult.OK)
         {
             System.Diagnostics.Process.Start("Explorer.exe", Environment.CurrentDirectory);
         }
     }
     catch (Exception)
     {
         lblConver.Enabled = false;
         MessageBox.Show("转换失败", "转换结果");
     }
 }
Пример #28
0
        protected void Converter(string path, string extension)
        {
            switch (extension)
            {
            case ".pdf":
                Aspose.Pdf.Document       pdfDoc = new Aspose.Pdf.Document(path);
                Aspose.Pdf.DocSaveOptions opts   = new Aspose.Pdf.DocSaveOptions();
                opts.Format = Aspose.Pdf.DocSaveOptions.DocFormat.Doc;
                opts.Mode   = Aspose.Pdf.DocSaveOptions.RecognitionMode.Flow;
                pdfDoc.Save(HttpContext.Current.Server.MapPath("Convert/input.doc"), opts);
                // Load in the document
                Document docpdf = new Document(HttpContext.Current.Server.MapPath("Convert/input.doc"));

                docpdf.Range.Replace("\t", "\n", false, true);
                docpdf.Save(HttpContext.Current.Server.MapPath("Input/input.txt"));
                break;

            case ".doc":
            case ".docx":
            case ".txt":
            case ".rtf":
            {
                // Load in the document
                Document doc = new Document(path);
                doc.Save(HttpContext.Current.Server.MapPath("Input/input.txt"));
                break;
            }
            }
            ConvertDocument(HttpContext.Current.Server.MapPath("Input/input.txt"));
        }
Пример #29
0
        public ActionResult PdfToDoc(HttpPostedFileBase pdfFile)
        {
            if (pdfFile != null)
            {
                var outputStream = new MemoryStream();
                var fileName     = Path.GetFileNameWithoutExtension(pdfFile.FileName);
                var fileExt      = Path.GetExtension(pdfFile.FileName);
                if (fileExt == ".pdf")
                {
                    string uploadedPath;
                    if (SaveFile(pdfFile, out uploadedPath))
                    {
                        var document    = new Aspose.Pdf.Document(uploadedPath);
                        var saveOptions = new Aspose.Pdf.DocSaveOptions();
                        document.Save(outputStream, saveOptions);

                        outputStream.Position = 0;
                        return(File(outputStream, "application/msword", fileName + ".doc"));
                    }
                    else
                    {
                        ModelState.AddModelError("", "File saving error : X001");
                        return(RedirectToAction("Index"));
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "File format error : X002");
                return(RedirectToAction("Index"));
            }

            return(RedirectToAction("Index"));
        }
Пример #30
0
        public static byte[] Tif2PDF(byte[] fileBuffer)
        {
            Aspose.Pdf.Document doc = new Aspose.Pdf.Document();
            // Add a page to pages collection of document

            MemoryStream mystream = new MemoryStream(fileBuffer);

            Image tiffImage  = Image.FromStream(mystream);
            int   frameCount = tiffImage.GetFrameCount(FrameDimension.Page);

            MemoryStream[] images       = new MemoryStream[frameCount];
            Guid           objGuid      = tiffImage.FrameDimensionsList[0];
            FrameDimension objDimension = new FrameDimension(objGuid);

            for (int i = 0; i < frameCount; i++)
            {
                tiffImage.SelectActiveFrame(objDimension, i);
                using (MemoryStream ms = new MemoryStream())
                {
                    tiffImage.Save(ms, ImageFormat.Bmp);
                    Aspose.Pdf.Page page = doc.Pages.Add();
                    Bitmap          b    = new Bitmap(ms);
                    page.Resources.Images.Add(ms);
                    page.PageInfo.Margin.Bottom = 0;
                    page.PageInfo.Margin.Top    = 0;
                    page.PageInfo.Margin.Left   = 0;
                    page.PageInfo.Margin.Right  = 0;
                    page.SetPageSize(b.Width, b.Height);

                    // Using GSave operator: this operator saves current graphics state
                    page.Contents.Add(new Aspose.Pdf.Operator.GSave());
                    // Create Rectangle and Matrix objects
                    Aspose.Pdf.Rectangle  rectangle = new Aspose.Pdf.Rectangle(0, 0, b.Width, b.Height);
                    Aspose.Pdf.DOM.Matrix matrix    = new Aspose.Pdf.DOM.Matrix(new double[] { rectangle.URX - rectangle.LLX, 0, 0, rectangle.URY - rectangle.LLY, rectangle.LLX, rectangle.LLY });

                    // Using ConcatenateMatrix (concatenate matrix) operator: defines how image must be placed
                    page.Contents.Add(new Aspose.Pdf.Operator.ConcatenateMatrix(matrix));
                    Aspose.Pdf.XImage ximage = page.Resources.Images[page.Resources.Images.Count];

                    // Using Do operator: this operator draws image
                    page.Contents.Add(new Aspose.Pdf.Operator.Do(ximage.Name));

                    // Using GRestore operator: this operator restores graphics state
                    page.Contents.Add(new Aspose.Pdf.Operator.GRestore());
                }
            }



            var pdfStream = new MemoryStream();

            doc.Save(pdfStream);
            // Close memoryStream object
            var buffer = pdfStream.ToArray();

            pdfStream.Close();
            mystream.Close();

            return(buffer);
        }
Пример #31
0
        public static void Run()
        {
            //ExStart: SearchTextWithDotNetRegex
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();

            // Create Regex object to find all words
            System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"[\S]+");

            // Open document
            Aspose.Pdf.Document document = new Aspose.Pdf.Document(dataDir + "SearchTextRegex.pdf");

            // Get a particular page
            Page page = document.Pages[1];

            // Create TextAbsorber object to find all instances of the input regex
            TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(regex);

            textFragmentAbsorber.TextSearchOptions.IsRegularExpressionUsed = true;

            // Accept the absorber for the page
            page.Accept(textFragmentAbsorber);

            // Get the extracted text fragments
            TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;

            // Loop through the fragments
            foreach (TextFragment textFragment in textFragmentCollection)
            {
                Console.WriteLine(textFragment.Text);
            }
            //ExEnd: SearchTextWithDotNetRegex
        }
Пример #32
0
        public static void Run()
        {
            // ExStart:1
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Text();

            // Create new document object
            Aspose.Pdf.Document document = new Aspose.Pdf.Document();
            Aspose.Pdf.Page     page     = document.Pages.Add();

            Aspose.Pdf.Text.TextFragment text = new Aspose.Pdf.Text.TextFragment("A quick brown fox jumped over the lazy dog. A quick brown fox jumped over the lazy dog. A quick brown fox jumped over the lazy dog. A quick brown fox jumped over the lazy dog. A quick brown fox jumped over the lazy dog. A quick brown fox jumped over the lazy dog. A quick brown fox jumped over the lazy dog. A quick brown fox jumped over the lazy dog.");

            // Initilize TextFormattingOptions for the text fragment and specify SubsequentLinesIndent value
            text.TextState.FormattingOptions = new Aspose.Pdf.Text.TextFormattingOptions()
            {
                SubsequentLinesIndent = 20
            };

            page.Paragraphs.Add(text);

            text = new Aspose.Pdf.Text.TextFragment("Line2");
            page.Paragraphs.Add(text);

            text = new Aspose.Pdf.Text.TextFragment("Line3");
            page.Paragraphs.Add(text);

            text = new Aspose.Pdf.Text.TextFragment("Line4");
            page.Paragraphs.Add(text);

            text = new Aspose.Pdf.Text.TextFragment("Line5");
            page.Paragraphs.Add(text);

            document.Save(dataDir + "SubsequentIndent_out.pdf", Aspose.Pdf.SaveFormat.Pdf);
            // ExEnd:1
        }
Пример #33
0
        ///<Summary>
        /// ConvertPdfToExcel to convert PDF to Excel
        ///</Summary>
        public Response ConvertPdfToExcel(string fileName, string folderName, string userEmail, string type)
        {
            type = type.ToLower();
            return(ProcessTask(fileName, folderName, "." + type, false, userEmail, false, delegate(string inFilePath, string outPath, string zipOutFolder)
            {
                // Open the source PDF document
                Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(inFilePath);

                // Instantiate ExcelSaveOptions object
                var saveOptions = new Aspose.Pdf.ExcelSaveOptions();
                if (type == "xlsx")
                {
                    // Specify the output format as XLSX
                    saveOptions.Format = Aspose.Pdf.ExcelSaveOptions.ExcelFormat.XLSX;
                    saveOptions.ConversionEngine = Aspose.Pdf.ExcelSaveOptions.ConversionEngines.NewEngine;
                }
                else if (type == "xml")
                {
                    // Specify the output format as SpreadsheetML
                    saveOptions.Format = Aspose.Pdf.ExcelSaveOptions.ExcelFormat.XMLSpreadSheet2003;
                }

                pdfDocument.Save(outPath, saveOptions);
            }));
        }
Пример #34
0
        ///<Summary>
        /// ConvertMDToPdf to convert MD to Pdf
        ///</Summary>

        public Response ConvertMarkownToPdf(string fileName, string folderName, string outputType)
        {
            return(ProcessTask(fileName, folderName, ".pdf", false, "", false,
                               delegate(string inFilePath, string outPath, string zipOutFolder)
            {
                Aspose.Pdf.MdLoadOptions options = new Aspose.Pdf.MdLoadOptions();
                Aspose.Pdf.Document document = new Aspose.Pdf.Document(inFilePath, options);
                if (outputType != "pdf")
                {
                    if (outputType == "pdf/a-1b")
                    {
                        document.Convert(new MemoryStream(), Pdf.PdfFormat.PDF_A_1B, Pdf.ConvertErrorAction.Delete);
                    }
                    if (outputType == "pdf/a-3b")
                    {
                        document.Convert(new MemoryStream(), Pdf.PdfFormat.PDF_A_2B, Pdf.ConvertErrorAction.Delete);
                    }
                    if (outputType == "pdf/a-2u")
                    {
                        document.Convert(new MemoryStream(), Pdf.PdfFormat.PDF_A_2U, Pdf.ConvertErrorAction.Delete);
                    }
                    if (outputType == "pdf/a-3u")
                    {
                        document.Convert(new MemoryStream(), Pdf.PdfFormat.PDF_A_3U, Pdf.ConvertErrorAction.Delete);
                    }
                }
                document.Save(outPath);
            }));
        }
        public static void InsertBlankPage()
        {
            // ExStart:InsertBlankPage
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdfFacades_TechnicalArticles();

            // Insert a blank page at the begining of concatenated file to display Table of Contents
            Aspose.Pdf.Document concatenated_pdfDocument = new Aspose.Pdf.Document(new FileStream(dataDir + "Concatenated_Table_Of_Contents.pdf", FileMode.Open));
            // Insert a empty page in a PDF
            concatenated_pdfDocument.Pages.Insert(1);
            // ExEnd:InsertBlankPage
        }
 /// <summary>
 /// Processes attachment to the <paramref name="outputStream" />.
 /// </summary>
 /// <param name="attachmentData">The attachment data.</param>
 /// <param name="outputStream">The output stream.</param>
 protected override void DoProcess(Stream attachmentData, Stream outputStream)
 {
     using (MemoryStream word = new MemoryStream())
     {
         Document wordDoc = new Document(attachmentData);
         wordDoc.Save(word, this.wordSave);
         Aspose.Pdf.Document wordPdf = new Aspose.Pdf.Document(word);
         using (var mergedPdf = new Aspose.Pdf.Document(outputStream))
         {
             mergedPdf.Pages.Add(wordPdf.Pages);
             mergedPdf.Save(outputStream);
         }
     }
 }
 /// <summary>
 /// Processes attachment to the <paramref name="outputStream" />.
 /// </summary>
 /// <param name="attachmentData">The attachment data.</param>
 /// <param name="outputStream">The output stream.</param>
 protected override void DoProcess(Stream attachmentData, Stream outputStream)
 {
     using (MemoryStream excel = new MemoryStream())
     {
         Workbook workBook = new Workbook(attachmentData);
         workBook.Save(excel, this.cellSave);
         Aspose.Pdf.Document excelPdf = new Aspose.Pdf.Document(excel);
         using (var mergedPdf = new Aspose.Pdf.Document(outputStream))
         {
             mergedPdf.Pages.Add(excelPdf.Pages);
             mergedPdf.Save(outputStream);
         }
     }
 }
        public static MemoryStream CreateMemoryStreamFromPdf(string faxPath)
        {
            InvokeAposePdfLicense();


            Logging.LogErrors(ConfigurationValues.ErrorLogPath, "Begin creating fax stream 1");                    

            MemoryStream pdfMemoryStream = new MemoryStream();
            Logging.LogErrors(ConfigurationValues.ErrorLogPath, "Begin creating fax stream 2");                    
            Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(faxPath);
            Logging.LogErrors(ConfigurationValues.ErrorLogPath, "Begin creating fax stream 3");                    
            pdfDocument.Save(pdfMemoryStream);
            Logging.LogErrors(ConfigurationValues.ErrorLogPath, "Begin creating fax stream 4");                    
            return pdfMemoryStream;
        }
        public static bool MergeTwoPDFDocuments(string documentToMerge, string mergedDocument)
        {
            InvokeAposePdfLicense();

            // Open the first document
            Aspose.Pdf.Document pdfDocument1 = new Aspose.Pdf.Document(documentToMerge);
            // Open the second document
            Aspose.Pdf.Document pdfDocument2 = new Aspose.Pdf.Document(mergedDocument);

            // Add pages of second document to the first
            pdfDocument1.Pages.Add(pdfDocument2.Pages);

            // Save concatenated output file
            pdfDocument1.Save(mergedDocument);
            return true;
        }
        private OperationResult ValidatePageCounts(string pathTofile)
        {
            OperationResult operationResult = new OperationResult();
            bool foundBarCode = false;
            string currentUser = Utility.GetUserName();
            int testCounter = 1;
            string currentPatientID = string.Empty;
            string currentTabID = string.Empty;

            Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(pathTofile);
            barCodeText = new List<ScannedDocument>();

            int pageCount = pdfDocument.Pages.Count;

            for (var i = 1; i <= pageCount; i++)
            {
                var converter = new PdfConverter();
                converter.BindPdf(pathTofile);
                converter.StartPage = i;
                converter.EndPage = i;
                converter.RenderingOptions.BarcodeOptimization = true;
                converter.Resolution = new Aspose.Pdf.Devices.Resolution(300);
                converter.DoConvert();
                MemoryStream stream = new MemoryStream();
                converter.GetNextImage(stream, ImageFormat.Png);
                using (BarCodeReader reader = new BarCodeReader(stream, BarCodeReadType.Code39Standard))
                {
                    while (reader.Read())
                    {
                        string[] barCodeDocument = reader.GetCodeText().Split('-');
                        ScannedDocument scannedDocument = new ScannedDocument();
                        scannedDocument.PatientID = barCodeDocument[0];
                        scannedDocument.TabID = barCodeDocument[1];
                        scannedDocument.CurrentPageNumber = int.Parse(barCodeDocument[2]);
                        scannedDocument.PageCount = int.Parse(barCodeDocument[3]);
                        scannedDocument.Text = reader.GetCodeText();
                        scannedDocument.FullPath = pathTofile;
                        scannedDocument.User = currentUser;
                        barCodeText.Add(scannedDocument);
                        foundBarCode = true;
                    }
                }
                converter.Close();
                converter.Dispose();

                if (foundBarCode != true)
                {
                    operationResult.Success = false;
                    operationResult.ErrorMessage = "Job Failed: Could not Read Bar Code";
                    return operationResult;
                }
                foundBarCode = false;
            }

            //Step 1 Check to be sure the number of pages in the document
            //matches the number of pages in the bar code
            int pdfPageCount = 0;
            int pdfPageCountCheck = 0;
            Aspose.Pdf.Document pdfDocumentPageCount = new Aspose.Pdf.Document(barCodeText[0].FullPath);
            pdfPageCount = pdfDocumentPageCount.Pages.Count;

            currentPatientID = barCodeText[0].PatientID;
            currentTabID = barCodeText[0].TabID;

            for (int i = 0; i < barCodeText.Count; i++)
            {
                try
                {
                    if (int.Parse(barCodeText[i].PatientID) < 1)
                    {
                        operationResult.Success = false;
                        operationResult.ErrorMessage = "Patient ID Invalid";
                        return operationResult;
                    }
                }
                catch 
                {
                    operationResult.Success = false;
                    operationResult.ErrorMessage = "Patient ID Invalid";
                    return operationResult;
                }
                try
                {
                    if (int.Parse(barCodeText[i].TabID) < 1)
                    {
                        operationResult.Success = false;
                        operationResult.ErrorMessage = "Tab ID Invalid";
                        return operationResult;
                    }
                }
                catch
                {
                    operationResult.Success = false;
                    operationResult.ErrorMessage = "Tab ID Invalid";
                    return operationResult;
                }

                if (testCounter == barCodeText[i].CurrentPageNumber && barCodeText[i].PageCount == barCodeText[i].CurrentPageNumber && barCodeText[i].PatientID == currentPatientID && barCodeText[i].TabID == currentTabID)
                {
                    //string[] barCodePageCount = barCodeText[i].Text.Split('-');
                    pdfPageCountCheck = pdfPageCountCheck + barCodeText[i].PageCount;
                    testCounter = 1;

                    if (barCodeText[i].PageCount == barCodeText[i].CurrentPageNumber)
                    {

                        try
                        {
                            currentPatientID = barCodeText[i + 1].PatientID;
                            currentTabID = barCodeText[i + 1].TabID;
                        }
                        catch { }
                    }
                }
                else
                {
                    if (testCounter == barCodeText[i].CurrentPageNumber && barCodeText[i].PatientID == currentPatientID && barCodeText[i].TabID == currentTabID)
                    {
                        testCounter++;
                    }
                    else
                    {
                        operationResult.Success = false;
                        operationResult.ErrorMessage = "Job Failed: Documents out of Order";
                        return operationResult;
                    }
                }
            }

            if (pageCount != pdfPageCountCheck)
            {
                operationResult.Success = false;
                operationResult.ErrorMessage = "Job Failed: Documents out of Order";
                return operationResult;
            }

            operationResult.Success = true;
            operationResult.ErrorMessage = "Job Confirmed";
            return operationResult;
        }
Пример #41
0
        /// <summary>
        /// Processes attachment to the <paramref name="outputStream" />.
        /// </summary>
        /// <param name="attachmentData">The attachment data.</param>
        /// <param name="outputStream">The output stream.</param>
        protected override void DoProcess(Stream attachmentData, Stream outputStream)
        {
            // Read the image into Byte array
            byte[] data = new byte[attachmentData.Length];
            attachmentData.Read(data, 0, (int)attachmentData.Length);

            Aspose.Pdf.Generator.Pdf pdf = new Aspose.Pdf.Generator.Pdf();

            // Add a section into the pdf document
            Aspose.Pdf.Generator.Section sec = pdf.Sections.Add();

            // Create an image object in the section
            Aspose.Pdf.Generator.Image image = new Aspose.Pdf.Generator.Image(sec);

            // Set the type of image using ImageFileType enumeration
            switch (this.fileExtension)
            {
                case ".jpg":
                case ".jpeg":
                    image.ImageInfo.ImageFileType = Aspose.Pdf.Generator.ImageFileType.Jpeg;
                    break;
                case ".gif":
                    image.ImageInfo.ImageFileType = Aspose.Pdf.Generator.ImageFileType.Gif;
                    break;
                case ".png":
                    image.ImageInfo.ImageFileType = Aspose.Pdf.Generator.ImageFileType.Png;
                    break;
                case ".bmp":
                    image.ImageInfo.ImageFileType = Aspose.Pdf.Generator.ImageFileType.Bmp;
                    break;
                case ".tif":
                    image.ImageInfo.ImageFileType = Aspose.Pdf.Generator.ImageFileType.Tiff;
                    break;
            }

            // Create a MemoryStream object from image Byte array
            MemoryStream ms = new MemoryStream(data);

            // Specify the image source as MemoryStream
            image.ImageInfo.ImageStream = ms;

            // Add image object into the Paragraphs collection of the section
            sec.Paragraphs.Add(image);

            // Save the Pdf
            using (MemoryStream img = new MemoryStream())
            {
                using (var mergedPdf = new Aspose.Pdf.Document(outputStream))
                {
                    try
                    {
                        pdf.Save(img);
                    }
                    catch (Exception)
                    {
                        image.ImageInfo.ImageFileType = Aspose.Pdf.Generator.ImageFileType.Bmp;
                        try
                        {
                            pdf.Save(img);
                        }
                        catch (Exception)
                        {
                            image.ImageInfo.ImageFileType = Aspose.Pdf.Generator.ImageFileType.Tiff;
                            try
                            {
                                pdf.Save(img);
                            }
                            catch (Exception)
                            {
                                return;
                            }
                        }
                    }

                    Aspose.Pdf.Document imgPdf = new Aspose.Pdf.Document(img);
                    mergedPdf.Pages.Add(imgPdf.Pages);
                    mergedPdf.Save(outputStream);
                }
            }

            // Close the MemoryStream Object
            ms.Close();
        }
        private void button3_Click(object sender, EventArgs e)
        {
            if (txtSearchWord.Text.Length < 1)
            {
                MessageBox.Show("Please select page to print", "Error");
                return;
            }
            
            
            this.Cursor = Cursors.WaitCursor;
            txtSearchWord.Text = txtSearchWord.Text + ",";

            string [] pagesToBEPrinted = txtSearchWord.Text.Split(',');

            try
            {
                Aspose.Pdf.License pdflicense = new Aspose.Pdf.License();
                
                pdflicense.SetLicense(System.Configuration.ConfigurationManager.AppSettings["aposePDFLicense"]);
                pdflicense.Embedded = true;

                //O2S.Components.PDF4NET.PDFDocument searchedPDF
                //    = new O2S.Components.PDF4NET.PDFDocument(batchFilePath);

                //searchedPDF.SerialNumber = "PDF4NET-AYBAM-8ARRR-B4EX2-OXGCC-KN2Q5";            

                //O2S.Components.PDF4NET.PDFDocument newPDF
                //    = new O2S.Components.PDF4NET.PDFDocument();

                //newPDF.SerialNumber = "PDF4NET-AYBAM-8ARRR-B4EX2-OXGCC-KN2Q5";


                //Open document
                
                //pdflicense.
                Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(batchFilePath);
                Aspose.Pdf.Document newPdf = new Aspose.Pdf.Document();
                
                //int pageCount = 1;
                //Loop through all the pages
                //foreach (Page pdfPage in pdfDocument.Pages)
                //{
                //    Document newDocument = new Document();
                //    newDocument.Pages.Add(pdfPage);
                //    newDocument.Save("page_" + pageCount + ".pdf");
                //    pageCount++;
               // }



                for (int i = 0; i < pagesToBEPrinted.Length - 1; i++)
                {
                    Aspose.Pdf.Page aPDFPage = pdfDocument.Pages[int.Parse(pagesToBEPrinted[i])];
                    newPdf.Pages.Add(aPDFPage);
                }
                ////pd.
                ////searchedPDF.
                newPdf.Save(batchFilePathPrintPDF);

                System.Diagnostics.Process.Start(batchFilePathPrintPDF);

                //Process p = new Process();
                //p.StartInfo = new ProcessStartInfo()
                //{
                //    CreateNoWindow = true,
                //    Verb = "print",
                //    FileName = batchFilePathPrintPDF //put the correct path here
                //};
                //p.Start();



                //SendToPrinter(batchFilePathPrintPDF);

                //_newPDF.Pages..RemoveAt(iPageToDelete - 1);
                //_newPDF.Save(_reviewDocument);
                //return true;
                this.Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                this.Cursor = Cursors.Default;
                MessageBox.Show("Error message is " + ex.Message, "Error", MessageBoxButtons.OK);
                //return false;
            }




            //string pathToDocument = batchFilePath;

            //// create index from PDF file
            //using (Stream pdfDocumentStreamToSearch = new FileStream(pathToDocument, FileMode.Open, FileAccess.Read))
            //{
            //    SearchIndex searchIndex = new SearchIndex(pdfDocumentStreamToSearch);

            //    // create document used for rendering
            //    using (Stream pdfDocumentStreamToRasterize = new FileStream(pathToDocument, FileMode.Open, FileAccess.Read))
            //    {
            //        document = new Document(pdfDocumentStreamToRasterize);

            //        // search text in PDF document and render pages containg results
            //        searchIndex.Search(SearchHandler, txtSearchWord.Text);
            //    }
            //}



            //    //SearchIndex searchIndex;

            //    //// so we have created the index already
            //    //if (searchDictionary.TryGetValue(loadedFilePath, out searchIndex))
            //    //{
            //    //    //e.SearchIndex = searchIndex;
            //    //}
            //    //else
            //    //{
            //    //    searchIndex = new SearchIndex(File.OpenRead(loadedFilePath));
            //    //    searchDictionary.Add(loadedFilePath, searchIndex);
            //    //    int ee = searchDictionary.Count;

            //    //    //e.SearchIndex = searchIndex;
            //    //}



            ////pdfViewer1.s
      }
        public static void CompletedCode()
        {
            // ExStart:CompletedCode
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdfFacades_TechnicalArticles();

            // Create PdfFileEditor object
            PdfFileEditor pdfEditor = new PdfFileEditor();
            // Create a MemoryStream object to hold the resultant PDf file
            using (MemoryStream Concatenated_Stream = new MemoryStream())
            {
                // Save concatenated output file
                pdfEditor.Concatenate(new FileStream(dataDir + "input1.pdf", FileMode.Open), new FileStream(dataDir + "input2.pdf", FileMode.Open), Concatenated_Stream);
                // Insert a blank page at the begining of concatenated file to display Table of Contents
                Aspose.Pdf.Document concatenated_pdfDocument = new Aspose.Pdf.Document(Concatenated_Stream);
                // Insert a empty page in a PDF
                concatenated_pdfDocument.Pages.Insert(1);

                // Hold the resultnat file with empty page added
                using (MemoryStream Document_With_BlankPage = new MemoryStream())
                {
                    // Save output file
                    concatenated_pdfDocument.Save(Document_With_BlankPage);

                    using (var Document_with_TOC_Heading = new MemoryStream())
                    {
                        // Add Table Of Contents logo as stamp to PDF file
                        PdfFileStamp fileStamp = new PdfFileStamp();
                        // Find the input file
                        fileStamp.BindPdf(Document_With_BlankPage);

                        // Set Text Stamp to display string Table Of Contents
                        Aspose.Pdf.Facades.Stamp stamp = new Aspose.Pdf.Facades.Stamp();
                        stamp.BindLogo(new FormattedText("Table Of Contents", System.Drawing.Color.Maroon, System.Drawing.Color.Transparent, Aspose.Pdf.Facades.FontStyle.Helvetica, EncodingType.Winansi, true, 18));
                        // Specify the origin of Stamp. We are getting the page width and specifying the X coordinate for stamp
                        stamp.SetOrigin((new PdfFileInfo(Document_With_BlankPage).GetPageWidth(1) / 3), 700);
                        // Set particular pages
                        stamp.Pages = new int[] { 1 };
                        // Add stamp to PDF file
                        fileStamp.AddStamp(stamp);

                        // Create stamp text for first item in Table Of Contents
                        var Document1_Link = new Aspose.Pdf.Facades.Stamp();
                        Document1_Link.BindLogo(new FormattedText("1 - Link to Document 1", System.Drawing.Color.Black, System.Drawing.Color.Transparent, Aspose.Pdf.Facades.FontStyle.Helvetica, EncodingType.Winansi, true, 12));
                        // Specify the origin of Stamp. We are getting the page width and specifying the X coordinate for stamp
                        Document1_Link.SetOrigin(150, 650);
                        // Set particular pages on which stamp should be displayed
                        Document1_Link.Pages = new int[] { 1 };
                        // Add stamp to PDF file
                        fileStamp.AddStamp(Document1_Link);

                        // Create stamp text for second item in Table Of Contents
                        var Document2_Link = new Aspose.Pdf.Facades.Stamp();
                        Document2_Link.BindLogo(new FormattedText("2 - Link to Document 2", System.Drawing.Color.Black, System.Drawing.Color.Transparent, Aspose.Pdf.Facades.FontStyle.Helvetica, EncodingType.Winansi, true, 12));
                        // Specify the origin of Stamp. We are getting the page width and specifying the X coordinate for stamp
                        Document2_Link.SetOrigin(150, 620);
                        // Set particular pages on which stamp should be displayed
                        Document2_Link.Pages = new int[] { 1 };
                        // Add stamp to PDF file
                        fileStamp.AddStamp(Document2_Link);

                        // Save updated PDF file
                        fileStamp.Save(Document_with_TOC_Heading);
                        fileStamp.Close();

                        // Now we need to add Heading for Table Of Contents and links for documents
                        PdfContentEditor contentEditor = new PdfContentEditor();
                        // Bind the PDF file in which we added the blank page
                        contentEditor.BindPdf(Document_with_TOC_Heading);
                        // Create link for first document
                        contentEditor.CreateLocalLink(new System.Drawing.Rectangle(150, 650, 100, 20), 2, 1, System.Drawing.Color.Transparent);
                        // Create link for Second document
                        // We have used   new PdfFileInfo("d:/pdftest/Input1.pdf").NumberOfPages + 2   as PdfFileInfo.NumberOfPages(..) returns the page count for first document
                        // And 2 is because, second document will start at Input1+1 and 1 for the page containing Table Of Contents.
                        contentEditor.CreateLocalLink(new System.Drawing.Rectangle(150, 620, 100, 20), new PdfFileInfo(dataDir + "Input1.pdf").NumberOfPages + 2, 1, System.Drawing.Color.Transparent);

                        // Save updated PDF
                        contentEditor.Save( dataDir + "Concatenated_Table_Of_Contents.pdf");
                    }
                }
            }
            // ExEnd:CompletedCode
        }
Пример #44
0
        /// <summary>
        /// 将pdf文档转换为图片的方法      
        /// </summary>
        /// <param name="originFilePath">pdf文件路径</param>
        /// <param name="imageOutputDirPath">图片输出路径,如果为空,默认值为pdf所在路径</param>       
        /// <param name="startPageNum">从PDF文档的第几页开始转换,如果为0,默认值为1</param>
        /// <param name="endPageNum">从PDF文档的第几页开始停止转换,如果为0,默认值为pdf总页数</param>       
        /// <param name="resolution">设置图片的像素,数字越大越清晰,如果为0,默认值为128,建议最大值不要超过1024</param>
        private void ConvertToImage(string originFilePath, string imageOutputDirPath, int startPageNum, int endPageNum, int resolution)
        {
            try
            {
                Aspose.Pdf.Document doc = new Aspose.Pdf.Document(originFilePath);

                if (doc == null)
                {
                    throw new Exception("pdf文件无效或者pdf文件被加密!");
                }

                if (imageOutputDirPath.Trim().Length == 0)
                {
                    imageOutputDirPath = Path.GetDirectoryName(originFilePath);
                }

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

                if (startPageNum <= 0)
                {
                    startPageNum = 1;
                }

                if (endPageNum > doc.Pages.Count || endPageNum <= 0)
                {
                    endPageNum = doc.Pages.Count;
                }

                if (startPageNum > endPageNum)
                {
                    int tempPageNum = startPageNum; startPageNum = endPageNum; endPageNum = startPageNum;
                }

                if (resolution <= 0)
                {
                    resolution = 128;
                }

                string imageNamePrefix = Path.GetFileNameWithoutExtension(originFilePath);
                for (int i = startPageNum; i <= endPageNum; i++)
                {
                    if (this.cancelled)
                    {
                        break;
                    }

                    MemoryStream stream = new MemoryStream();
                    string imgPath = Path.Combine(imageOutputDirPath, imageNamePrefix) + "_" + i.ToString("000") + ".jpg";
                    Aspose.Pdf.Devices.Resolution reso = new Aspose.Pdf.Devices.Resolution(resolution);
                    Aspose.Pdf.Devices.JpegDevice jpegDevice = new Aspose.Pdf.Devices.JpegDevice(reso, 100);
                    jpegDevice.Process(doc.Pages[i], stream);

                    Image img = Image.FromStream(stream);
                    Bitmap bm = ESBasic.Helpers.ImageHelper.Zoom(img, 0.6f);
                    bm.Save(imgPath, ImageFormat.Jpeg);
                    img.Dispose();
                    stream.Dispose();
                    bm.Dispose();

                    System.Threading.Thread.Sleep(200);
                    if (this.ProgressChanged != null)
                    {
                        this.ProgressChanged(i - 1, endPageNum);
                    }
                }

                if (this.cancelled)
                {
                    return;
                }

                if (this.ConvertSucceed != null)
                {
                    this.ConvertSucceed();
                }
            }
            catch (Exception ex)
            {
                if (this.ConvertFailed != null)
                {
                    this.ConvertFailed(ex.Message);
                }
            }
        }
Пример #45
0
    protected void DosyalariSistemeUygunBicimdeYukle()
    {
        try
        {
            new Aspose.Pdf.License().SetLicense(LicenseHelper.License.LStream);
            UploadedFile file = upl.UploadedFiles[0];
            EFDal e = new EFDal();
            Guid DosyaAdi = Guid.NewGuid();
            var usr = UserManager.GetCurrentUser();
            string usrName = usr.Identity.Name;

            int BolgeKodu = e.kal_BolgeKoduDon(usrName);

            string dosyaYolu = Server.MapPath("~/DosyaSistemi/");
            dosyaYolu += BolgeKodu.ToString();
            dosyaYolu += '\\' + DateTime.Now.Year.ToString() + '\\' + DosyaAdi.ToString() +file.GetExtension();

            string DosyaAdiveUzantisiOlmadandosyaYolu = Server.MapPath("~/DosyaSistemi/") + BolgeKodu.ToString() + '\\' +
                                                        DateTime.Now.Year.ToString() + '\\';

            //string targetFolder = dosyaYolu;
            //string targetFileName = Path.Combine(targetFolder, DosyaAdi + file.GetExtension());
            string targetFileName = dosyaYolu;
            file.SaveAs(targetFileName);

            //Dosya yüklendiği orijinal hali ile sitemde su anda, bu dosyayı pdf e çevirmemiz gerekli şimdi
            switch (file.GetExtension())
            {
                case ".doc":
                    PDFCevirici.WordToPDF(targetFileName, DosyaAdiveUzantisiOlmadandosyaYolu + DosyaAdi + ".pdf");
                    break;
                case ".docx":
                    PDFCevirici.DOCXToPDF(targetFileName, DosyaAdiveUzantisiOlmadandosyaYolu + DosyaAdi + ".pdf");
                    break;
                case ".xls":
                    PDFCevirici.ExcelToPDF(targetFileName, DosyaAdiveUzantisiOlmadandosyaYolu + DosyaAdi + ".pdf");
                    break;
                case ".xlsx":
                    PDFCevirici.ExcelToPDF(targetFileName, DosyaAdiveUzantisiOlmadandosyaYolu + DosyaAdi + ".pdf");
                    break;

                case ".pdf":
                    //Hiçbirşey yapma
                    break;
            }

            string kapakPDFDosyasi = e.IstIddenKapakPDFninPathiniDon(Convert.ToInt32(Request["IstId"]));
            string veriSayfalariIcinSonucDosyaAdresi = DosyaAdiveUzantisiOlmadandosyaYolu + DosyaAdi + ".pdf";

            Aspose.Pdf.Document pdfKapak = new Aspose.Pdf.Document(kapakPDFDosyasi);
            Aspose.Pdf.Document pdfVeri = new Aspose.Pdf.Document(veriSayfalariIcinSonucDosyaAdresi);

            pdfKapak.Pages.Add(pdfVeri.Pages);
            pdfKapak.Save(kapakPDFDosyasi);

            lblUplUyari.ForeColor = System.Drawing.Color.LimeGreen;
            //Şimdi gönderilen sertifika verisi dosyasını veritabanına işlemek için path ve dosyaadi bilgisini oluştur.
            //string bak = dosyaYolu;
            //2 nolu dokuman Sertifika verisine karsilik geliyor

            //Burada gridi yeniden bağlamak gerekiyor
            GridiBagla();
            File.Delete(DosyaAdiveUzantisiOlmadandosyaYolu + DosyaAdi + file.GetExtension());
            File.Delete(veriSayfalariIcinSonucDosyaAdresi);//veri sayfalarından oluşan pdf i de sil
            e.spImzaliDosyalaraEkle(Convert.ToInt32(Request["IstId"]), DosyaAdi + ".pdf", 2, Guid.Empty,
               e.UserNamedenUserIdDon(usrName), dosyaYolu, ".pdf");
            //Şİmdi bu dosya kal. yapan ve müdür tarafından e-imza bekliyor. Bu yızden bunu imzabekleyenler tablosuna ekle
            int imzaliDosyaId = e.IstIddenSertifikaKapagininImzaliDosyalarIdsiniDon(Convert.ToInt32(Request["IstId"]));
            e.spImzaBekleyenDokumanlaraEkle(imzaliDosyaId, e.UserNamedenPersonelUNDon(Context.User.Identity.Name), false, true, Convert.ToInt32(Request["IstId"]));
            lblUplUyari.Text = "Dosya başarıyla yüklenmiştir...";
            GridiBagla();
        }
        catch (Exception)
        {
            // UploadedFile file = upl.UploadedFiles[0];
            lblUplUyari.ForeColor = System.Drawing.Color.Red;
            lblUplUyari.Text = "Dosya yüklenemedi! Dosya boyutu 10 MB'dan büyük olamaz. Lütfen kontrol ediniz";
        }
    }
 private static int GetPageCount(string faxPath)
 {
     Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(faxPath);
     return pdfDocument.Pages.Count;
 }
Пример #47
0
        public void UpdatePdf(IEditableRoot item, IFileProcess file)
        {
            if (file == null || item == null || string.IsNullOrEmpty(file.FileName)) return;

            var sysOptions = SystemOptionsInfo.GetSystemOptionsInfo();
            if (sysOptions == null)
                return;

            if (file.UseReport.HasValue && file.UseReport.Value)
            {
                GeneratePdfFromReport(item, file, sysOptions);
                return;
            }

            if (!file.IsReadyForPdf())
            {
                return;
            }

            if (!file.IsPdfWithReport())
            {
                return;
            }

            DownloadDocument(
                file.FileName,
                sysOptions,
                fileStream =>
                {
                    if (fileStream == null || fileStream.Length == 0)
                        return;

                    try
                    {
                        var isLandscape = false;

                        using (var documentStream = new MemoryStream())
                        {
                            if (!SavePdfToStream(file.FileName, fileStream, documentStream, ref isLandscape)) return;

                            //watermarks
                            using (var pdfDoc = new Aspose.Pdf.Document(documentStream))
                            {
                                if (pdfDoc.Pages.Count == 0)
                                    return;

                                var watermarkReport = isLandscape ? file.WatermarkLandscapeReportName : file.WatermarkPortraitReportName;
                                if (!string.IsNullOrEmpty(watermarkReport))
                                {
                                    var ms = GetReportStream(item, watermarkReport);

                                    var watermarkPdf = new Aspose.Pdf.Document(ms);
                                    if (watermarkPdf.Pages.Count > 0)
                                    {
                                        var pageStamp = new Aspose.Pdf.PdfPageStamp(watermarkPdf.Pages[1]) { Background = false, Opacity = 0.0 };

                                        var page = (file.FirstPageWatermark.HasValue && file.FirstPageWatermark.Value) ? 1 : 2;
                                        for (var i = page; i <= pdfDoc.Pages.Count; i++)
                                            pdfDoc.Pages[i].AddStamp(pageStamp);
                                    }
                                }

                                //cover page
                                var coverPageReport = isLandscape ? file.CoverPageLandscapeReportName : file.CoverPagePortraitReportName;
                                if (!string.IsNullOrEmpty(coverPageReport))
                                {
                                    var ms = GetReportStream(item, coverPageReport);

                                    var coverPagePdf = new Aspose.Pdf.Document(ms);
                                    pdfDoc.Pages.Insert(1, coverPagePdf.Pages);
                                }

                                //Appendix
                                var appendixReport = isLandscape ? file.AppendixLandscapeReportName : file.AppendixPortraitReportName;
                                if (!string.IsNullOrEmpty(appendixReport))
                                {
                                    var ms = GetReportStream(item, appendixReport);

                                    var appendixePdf = new Aspose.Pdf.Document(ms);
                                    pdfDoc.Pages.Insert(pdfDoc.Pages.Count + 1, appendixePdf.Pages);
                                }

                                var outputStream = new MemoryStream();
                                pdfDoc.Save(outputStream);

								var newFileNameWithPdfExtension = string.IsNullOrEmpty(file.ConvertedFileName) ?
									FileHelper.GetNewFileNameWithPdfExtension(file.FileName) :
									file.ConvertedFileName;

								UploadFile(newFileNameWithPdfExtension, outputStream, sysOptions);

                                if (file.ConvertedFileName != newFileNameWithPdfExtension)
                                {
                                    file.ConvertedFileName = newFileNameWithPdfExtension;
                                    ((ISavable)file).Save();
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Logger.Log(LogSeverity.Error, "FileManager.UpdatePdf", e.ToString());
                    }
                });
        }
Пример #48
0
        private static bool SavePdfToStream(string inputFile, MemoryStream fileStream, MemoryStream documentStream, ref bool isLandscape)
        {
            var extension = Path.GetExtension(inputFile);
            if (string.IsNullOrEmpty(extension))
                throw new ArgumentException(inputFile);

            try
            {
                fileStream.Position = 0;
                switch (extension.ToUpperInvariant())
                {
                    case ".DOC":
                    case ".DOCX":
                    case ".RTF":
                    case ".DOT":
                    case ".DOTX":
                        var doc = new Aspose.Words.Document(fileStream);
                        if (doc.PageCount > 0)
                        {
                            var pageInfo = doc.GetPageInfo(0);
                            isLandscape = pageInfo.WidthInPoints > pageInfo.HeightInPoints;
                        }
                        doc.Save(documentStream, Aspose.Words.SaveFormat.Pdf);
                        break;
                    case ".XLS":
                    case ".XLSX":
                        var workbook = new Aspose.Cells.Workbook(fileStream);
                        for (var i = 0; i < workbook.Worksheets.Count; i++)
                        {
                            if (!workbook.Worksheets[i].IsVisible) continue;
                            isLandscape = workbook.Worksheets[i].PageSetup.Orientation == Aspose.Cells.PageOrientationType.Landscape;
                            break;
                        }
                        workbook.Save(documentStream, Aspose.Cells.SaveFormat.Pdf);
                        break;
                    //Microsoft Visio 
                    case ".VSD":
                    case ".VSS":
                    case ".VST":
                    case ".VSX":
                    case ".VTX":
                    case ".VDW":
                    case ".VDX":
                        var vsdDiagram = new Aspose.Diagram.Diagram(fileStream);
                        if (vsdDiagram.Pages.Count > 0)
                            isLandscape = vsdDiagram.Pages[0].PageSheet.PrintProps.PrintPageOrientation.Value == Aspose.Diagram.PrintPageOrientationValue.Landscape;
                        vsdDiagram.Save(documentStream, Aspose.Diagram.SaveFileFormat.PDF);
                        break;
                    //Microsoft Project
                    case ".MPP":
                        var project = new Aspose.Tasks.Project(fileStream);
                        project.Save(documentStream, Aspose.Tasks.Saving.SaveFileFormat.PDF);
                        isLandscape = true;
                        break;
                    //PowerPoint
                    case ".PPT":
                    case ".PPS":
                    case ".POT":
                        using (var pres = new Aspose.Slides.Presentation(fileStream))
                        {
                            isLandscape = pres.SlideSize.Size.Width > pres.SlideSize.Size.Height;
                            pres.Save(documentStream, Aspose.Slides.Export.SaveFormat.Pdf);
                        }
                        break;
                    case ".PPTX":
                    case ".PPSX":
                    case ".POTX":
                        //case ".XPS":
                        using (var presEx = new Aspose.Slides.Presentation(fileStream))
                        {
                            isLandscape = presEx.SlideSize.Orientation == Aspose.Slides.SlideOrienation.Landscape;
                            presEx.Save(documentStream, Aspose.Slides.Export.SaveFormat.Pdf);
                        }
                        break;

                    case ".PDF":
                        {
                            using (var pdf = new Aspose.Pdf.Document(fileStream))
                            {
                                var page = pdf.Pages.OfType<Aspose.Pdf.Page>().FirstOrDefault();
                                if (page != null && page.MediaBox != null)
                                {
                                    isLandscape = page.MediaBox.Width > page.MediaBox.Height;
                                }
                            }

                            fileStream.Seek(0, SeekOrigin.Begin);
                            fileStream.CopyTo(documentStream);
                        }

                        break;
                }
            }
            finally
            {
                fileStream.Close();
            }

            return true;
        }
        public void WithUpdateFields()
        {
            Document doc = DocumentHelper.CreateDocumentFillWithDummyText();

            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.UpdateFields = true;

            doc.Save(MyDir + @"\Artifacts\UpdateFields_False.pdf", pdfSaveOptions);

            Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(MyDir + @"\Artifacts\UpdateFields_False.pdf");

            //Get text fragment by search string
            TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("Page 1 of 2");
            pdfDocument.Pages.Accept(textFragmentAbsorber);

            //Assert that fields are updated
            Assert.AreEqual("Page 1 of 2", textFragmentAbsorber.TextFragments[1].Text);
        }