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;
        }
Esempio n. 2
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
            });
        }
Esempio n. 3
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");
        }
Esempio n. 4
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
        }
Esempio n. 5
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);
        }
Esempio n. 6
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"));
        }
Esempio n. 7
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);
            }));
        }
        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
        }
Esempio n. 9
0
        private void CreatePdfFile_1()
        {
            //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();

            //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!");
            }
        }
        public static void Run()
        {
            //ExStart: TextAlignmentForTableRowContent
            var dataDir = RunExamples.GetDataDir_AsposePdf_Tables();

            // Create PDF document
            Aspose.Pdf.Document doc = new Aspose.Pdf.Document();
            // Initializes a new instance of the Table
            Aspose.Pdf.Table table = new Aspose.Pdf.Table();
            // Set the table border color as LightGray
            table.Border = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .5f, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray));
            // set the border for table cells
            table.DefaultCellBorder = new Aspose.Pdf.BorderInfo(Aspose.Pdf.BorderSide.All, .5f, Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray));
            // create a loop to add 10 rows
            for (int row_count = 0; row_count < 10; row_count++)
            {
                // add row to table
                Aspose.Pdf.Row row = table.Rows.Add();
                row.VerticalAlignment = VerticalAlignment.Center;

                row.Cells.Add("Column (" + row_count + ", 1)" + DateTime.Now.Ticks);
                row.Cells.Add("Column (" + row_count + ", 2)");
                row.Cells.Add("Column (" + row_count + ", 3)");
            }
            Page tocPage = doc.Pages.Add();

            // Add table object to first page of input document
            tocPage.Paragraphs.Add(table);
            // Save updated document containing table object
            doc.Save(dataDir + "43620_ByWords_out.pdf");
            //ExEnd: TextAlignmentForTableRowContent
        }
        public static void Run()
        {
            // ExStart:ConvertImageStreamtoPDF
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Images();

            // Instantiate Document instance by calling its empty constructor
            Aspose.Pdf.Document pdf1 = new Aspose.Pdf.Document();
            // Add a Page into the pdf document
            Aspose.Pdf.Page sec = pdf1.Pages.Add();

            // Create a FileStream object to read the imag file
            FileStream fs = File.OpenRead(dataDir + "aspose.jpg");

            // Read the image into Byte array
            byte[] data = new byte[fs.Length];
            fs.Read(data, 0, data.Length);

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

            // Create an image object
            Aspose.Pdf.Image imageht = new Aspose.Pdf.Image();

            // Specify the image source as MemoryStream
            imageht.ImageStream = ms;
            // Add image object into the Paragraphs collection of the section
            sec.Paragraphs.Add(imageht);

            // Save the Pdf
            pdf1.Save(dataDir + "ConvertMemoryStreamImageToPdf_out.pdf");
            // Close the MemoryStream Object
            ms.Close();
            // ExEnd:ConvertImageStreamtoPDF
        }
        public static void Run()
        {
            // ExStart:1
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_StampsWatermarks();

            // Instantiate Document instance
            Aspose.Pdf.Document pdf = new Aspose.Pdf.Document();
            // Add a Page into the pdf document
            Aspose.Pdf.Page page = pdf.Pages.Add();

            // Initializes a new instance of the FloatingBox class
            Aspose.Pdf.FloatingBox box1 = new Aspose.Pdf.FloatingBox(140, 80);
            // Float value that indicates left position of the paragraph
            box1.Left = 2;
            // Float value that indicates top position of the paragraph
            box1.Top = 10;
            // Add the macros to the paragraphs collection of the FloatingBox
            box1.Paragraphs.Add(new Aspose.Pdf.Text.TextFragment("Page: ($p/ $P )"));
            // Add a floatingBox to the page
            page.Paragraphs.Add(box1);

            // Save the document
            pdf.Save(dataDir + "PageNumberinHeaderFooterUsingFloatingBox_out.pdf");
            // ExEnd:1
        }
Esempio n. 13
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 Run()
        {
            // ExStart:1
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();

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

            Aspose.Pdf.Page sec1            = pdf.Pages.Add();
            Aspose.Pdf.Text.TextFragment t1 = new Aspose.Pdf.Text.TextFragment("paragraph 3 segment");
            sec1.Paragraphs.Add(t1);

            Aspose.Pdf.Text.TextSegment seg1 = new Aspose.Pdf.Text.TextSegment();
            t1.Text = "paragraph 3 segment 1";
            t1.TextState.ForegroundColor = Color.Red;
            t1.TextState.FontSize        = 12;

            Aspose.Pdf.Image image1 = new Aspose.Pdf.Image();
            image1.File = dataDir + "test_image.png";

            Aspose.Pdf.FloatingBox box1 = new Aspose.Pdf.FloatingBox(117, 21);
            sec1.Paragraphs.Add(box1);

            box1.Left = -4;
            box1.Top  = -4;
            box1.Paragraphs.Add(image1);

            pdf.Save(dataDir + "CreateMultiLayerPdf_out.pdf");
            // ExEnd:1
        }
Esempio n. 15
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!");
            }
        }
Esempio n. 16
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);
        }
        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
        }
Esempio n. 18
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
        }
Esempio n. 19
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();
                }
            }
        }
Esempio n. 20
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"));
        }
Esempio n. 21
0
        public Aspose.Words.Document convertirPDFBase64ADocx(String base64Pdf)
        {
            var binaryPdf = Convert.FromBase64String(base64Pdf);

            Aspose.Words.Document finalDoc = null;
            using (var pdfInput = new MemoryStream(binaryPdf))
            {
                Aspose.Pdf.Document       pdfDoc      = new Aspose.Pdf.Document(pdfInput);
                Aspose.Pdf.DocSaveOptions saveOptions = new Aspose.Pdf.DocSaveOptions();
                saveOptions.Format = Aspose.Pdf.DocSaveOptions.DocFormat.DocX;

                /*saveOptions.RasterImagesSavingMode = Aspose.Pdf.HtmlSaveOptions.RasterImagesSavingModes.AsEmbeddedPartsOfPngPageBackground;
                 * saveOptions.FontSavingMode = Aspose.Pdf.HtmlSaveOptions.FontSavingModes.SaveInAllFormats;
                 * saveOptions.PartsEmbeddingMode = Aspose.Pdf.HtmlSaveOptions.PartsEmbeddingModes.EmbedAllIntoHtml;
                 * saveOptions.LettersPositioningMethod = Aspose.Pdf.HtmlSaveOptions.LettersPositioningMethods.UseEmUnitsAndCompensationOfRoundingErrorsInCss;
                 * saveOptions.SplitIntoPages = false;
                 * saveOptions.CustomHtmlSavingStrategy = new Aspose.Pdf.HtmlSaveOptions.HtmlPageMarkupSavingStrategy(SavingToStream);
                 */
                string tempFile = Path.GetTempFileName();
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
                pdfDoc.Save(tempFile, saveOptions);
                finalDoc = new Aspose.Words.Document(tempFile);
                File.Delete(tempFile);
            }
            return(finalDoc);
        }
Esempio n. 22
0
        public static cConversionResult ConvertFile(string drawingName, string polygonID)
        {
            cConversionResult ConversionResult = new cConversionResult();
            string            URL = null;



            try
            {
                URL = string.Format(ExportSettings.ApertureWebServiceUrl111, drawingName, polygonID);

                // string RemoteURL = "https://www9.cor-asp.ch/ApWebServices/ApDrawingPDFs.aspx?p=SwisscomTest_Portal&d={0}&L=Z_Export&S=Z_Export";
                // string LocalURL = "http://vm-wincasa/ApWebServices/ApDrawingPDFs.aspx?p=Swisscom_Portal&d={0}&L=Z_Export&S=Z_Export";

                //baReturnValue = DownloadPdf("https://www9.cor-asp.ch/ApWebServices/ApDrawingPDFs.aspx?p=SwisscomTest_Portal&d=1002_GB01_OG01_0000&L=Z_Export");
                //baReturnValue = DownloadPdf("http://vm-wincasa/ApWebServices/ApDrawingPDFs.aspx?p=Swisscom_Portal&d=1002_GB01_OG01_0000&L=Z_Export");
                //baReturnValue = DownloadPdf("http://vm-wincasa/ApWebServices/ApDrawingPDFs.aspx?p=Swisscom_Portal&d=1010_GB01_UG02_0000&L=Z_Export");
                // http://vm-wincasa/ApWebServices/ApDrawingPDFs.aspx?p=Swisscom_Portal&d=1010_GB01_UG02_0000&L=Z_Export&S=Z_Export

                ConversionResult.PDF = DownloadPdf(URL);
            }
            catch (System.Net.WebException we)
            {
                System.Console.WriteLine(we.Message);
            }
            catch (System.Exception ex)
            {
                System.Console.WriteLine(ex.Message);
            }


#if WITH_ASPOSE
            string temporaryOutFileName = System.IO.Path.GetTempFileName();

            using (System.IO.Stream ms = new System.IO.MemoryStream(ConversionResult.PDF))
            {
                // using (Aspose.Pdf.Document doc = new Aspose.Pdf.Document(@"dwg17.pdf"))
                using (Aspose.Pdf.Document doc = new Aspose.Pdf.Document(ms))
                {
                    Aspose.Pdf.SvgSaveOptions saveOptions = new Aspose.Pdf.SvgSaveOptions();

                    // do not compress SVG image to Zip archive
                    saveOptions.CompressOutputToZipArchive = false;

                    doc.Save(temporaryOutFileName, saveOptions);
                } // End Using doc

                ms.Close();
            } // End Using ms

            ConversionResult.SVG = RemoveEvalString(temporaryOutFileName, URL);
            if (System.IO.File.Exists(temporaryOutFileName))
            {
                System.IO.File.Delete(temporaryOutFileName);
            }
#endif

            return(ConversionResult);
        } // End Function ConvertFile
        public static void Run()
        {
            // ExStart:CreatePDFA1WithAsposePdf
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();

            Aspose.Pdf.Document pdf1 = new Aspose.Pdf.Document();
            // Add a page into the pdf document
            pdf1.Pages.Add().Paragraphs.Add(new TextFragment("Hello World!"));
            MemoryStream ms = new MemoryStream();

            // Save the document
            pdf1.Save(ms);
            pdf1.Convert(new MemoryStream(), PdfFormat.PDF_A_1A, ConvertErrorAction.Delete);
            pdf1.Save(dataDir + "CreatePdfA1_out.pdf");
            // ExEnd:CreatePDFA1WithAsposePdf
        }
        public HttpResponseMessage DocumentInformation(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 lc = new LayoutCollector(doc);
                //PrepareInternalLinks(doc, lc);

                var lst = new List <PageView>(doc.Pages.Count);
                for (int i = 1; i <= doc.Pages.Count; i++)
                {
                    var pageInfo = doc.Pages[i];
                    var size     = pageInfo.Rect;
                    lst.Add(new PageView()
                    {
                        width  = size.Width,
                        height = size.Height,
                        angle  = 0,
                        number = i
                    });

                    using (var newDoc = new Document())
                    {
                        newDoc.Pages.Add(pageInfo);
                        newDoc.Save(Config.Configuration.OutputDirectory + Opts.FolderName + $"/page{i}.html",
                                    new Aspose.Pdf.HtmlSaveOptions
                        {
                            DocumentType             = Pdf.HtmlDocumentType.Html5,
                            FixedLayout              = true,
                            PartsEmbeddingMode       = Aspose.Pdf.HtmlSaveOptions.PartsEmbeddingModes.EmbedAllIntoHtml,
                            LettersPositioningMethod = Aspose.Pdf.HtmlSaveOptions.LettersPositioningMethods.UseEmUnitsAndCompensationOfRoundingErrorsInCss,
                            RasterImagesSavingMode   = Aspose.Pdf.HtmlSaveOptions.RasterImagesSavingModes.AsEmbeddedPartsOfPngPageBackground,
                            FontSavingMode           = Aspose.Pdf.HtmlSaveOptions.FontSavingModes.SaveInAllFormats,
                            SplitIntoPages           = false,
                            SplitCssIntoPages        = false,
                        });
                    }
                }

                //return Request.CreateResponse(HttpStatusCode.OK, new PageParametersResponse(request.fileName, lst, PrepareNavigationPaneList(doc, lc)));
                return(Request.CreateResponse(HttpStatusCode.OK, new PageParametersResponse(request.fileName, lst, null)));
            }
            catch (Exception ex)
            {
                return(ExceptionResponse(ex));
            }
        }
Esempio n. 25
0
        public static void Run()
        {
            // ExStart:1
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion();

            // Get a list of tiff image files
            string[] files = System.IO.Directory.GetFiles(dataDir, "*.tif");

            // Instantiate a Document object
            Aspose.Pdf.Document doc = new Aspose.Pdf.Document();

            // Navigate through the files and them in the pdf file
            foreach (string myFile in files)
            {
                // Load all tiff files in byte array
                FileStream fs       = new FileStream(myFile, FileMode.Open, FileAccess.Read);
                byte[]     tmpBytes = new byte[fs.Length];
                fs.Read(tmpBytes, 0, Convert.ToInt32(fs.Length));

                MemoryStream mystream = new MemoryStream(tmpBytes);
                Bitmap       b        = new Bitmap(mystream);
                // Create a new Page in the Pdf document
                Aspose.Pdf.Page currpage = doc.Pages.Add();

                // Set margins so image will fit, etc.
                currpage.PageInfo.Margin.Top    = 5;
                currpage.PageInfo.Margin.Bottom = 5;
                currpage.PageInfo.Margin.Left   = 5;
                currpage.PageInfo.Margin.Right  = 5;

                currpage.PageInfo.Width  = (b.Width / b.HorizontalResolution) * 72;
                currpage.PageInfo.Height = (b.Height / b.VerticalResolution) * 72;

                // Create an image object
                Aspose.Pdf.Image image1 = new Aspose.Pdf.Image();

                // Add the image into paragraphs collection of the page
                currpage.Paragraphs.Add(image1);

                // Set IsBlackWhite property to true for performance improvement
                image1.IsBlackWhite = true;
                // Set the ImageStream to a MemoryStream object
                image1.ImageStream = mystream;
                // Set desired image scale
                image1.ImageScale = 0.95F;
            }

            // Save the Pdf
            doc.Save(dataDir + "PerformaceImprovement_out.pdf");
            // ExEnd:1
        }
Esempio n. 26
0
        ///<Summary>
        /// ConvertEPUBToPdf to convert EPUB to Pdf
        ///</Summary>
        public Response ConvertEPUBToPdf(string fileName, string folderName, string userEmail)
        {
            return(ProcessTask(fileName, folderName, ".pdf", false, userEmail, false, delegate(string inFilePath, string outPath, string zipOutFolder)
            {
                // Instantiate LoadOption object using EPUB load option
                Aspose.Pdf.EpubLoadOptions epubload = new Aspose.Pdf.EpubLoadOptions();

                // Create document object
                Aspose.Pdf.Document document = new Aspose.Pdf.Document(inFilePath, epubload);

                // Save the document in PDF format.
                document.Save(outPath);
            }));
        }
 /// <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);
         }
     }
 }
Esempio n. 28
0
        ///<Summary>
        /// ConvertPdfToPPTX to convert PDF to PPTX
        ///</Summary>
        public Response ConvertPdfToPPTX(string fileName, string folderName, string userEmail)
        {
            return(ProcessTask(fileName, folderName, ".pptx", false, userEmail, false, delegate(string inFilePath, string outPath, string zipOutFolder)
            {
                // Load PDF document
                Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(inFilePath);

                // Instantiate PptxSaveOptions instance
                Aspose.Pdf.PptxSaveOptions options = new Aspose.Pdf.PptxSaveOptions();

                // Save the output in PPTX format
                pdfDocument.Save(outPath, options);
            }));
        }
Esempio n. 29
0
        ///<Summary>
        /// ConvertPdfToXPS to convert PDF to XPS
        ///</Summary>

        public Response ConvertPdfToXPS(string fileName, string folderName, string userEmail)
        {
            return(ProcessTask(fileName, folderName, ".xps", false, userEmail, false, delegate(string inFilePath, string outPath, string zipOutFolder)
            {
                // Load PDF document
                Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(inFilePath);

                // Instantiate XPS Save options
                Aspose.Pdf.XpsSaveOptions saveOptions = new Aspose.Pdf.XpsSaveOptions();

                // Save the XPS document
                pdfDocument.Save(outPath, saveOptions);
            }));
        }
 /// <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);
         }
     }
 }
        public static void Run()
        {
            // ExStart:1
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments();

            //Create pdf document
            Aspose.Pdf.Document pdf = new Aspose.Pdf.Document();
            //Bind XML and XSLT files to the document
            pdf.BindXml(dataDir + "\\Breakfast.xml", dataDir + "\\Breakfast.xslt");
            //Save the document
            pdf.Save(dataDir + "BreakfastMenu.pdf");
            // ExEnd:1
        }
        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;
        }
Esempio n. 34
0
        public MemoryStream ToPDF <T>(T entity, string xslt)
        {
            MemoryStream xmlStream = entity.TransformXsltStream(xslt);

            Aspose.Pdf.Document pdfDoc = new Aspose.Pdf.Document();
            pdfDoc.BindXml(xmlStream);

            pdfDoc.Info.Author       = UserIdentity.UserName;
            pdfDoc.Info.CreationDate = DateTime.Now;
            pdfDoc.Info.Keywords     = MarkelConfiguration.ApplicationName;

            MemoryStream pdfStream = new MemoryStream();

            pdfDoc.Save(pdfStream);
            return(pdfStream);
        }
Esempio n. 35
0
        public static byte[] Img2PDF(byte[] fileBuffer)
        {
            Aspose.Pdf.Document doc = new Aspose.Pdf.Document();
            // Add a page to pages collection of document
            Aspose.Pdf.Page page     = doc.Pages.Add();
            MemoryStream    mystream = new MemoryStream(fileBuffer);
            // Instantiate BitMap object with loaded image stream
            Bitmap b = new Bitmap(mystream);

            // Set margins so image will fit, etc.
            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);

            //page.CropBox = new Aspose.Pdf.Rectangle(0, 0, b.Width, b.Height);

            page.Resources.Images.Add(mystream);

            // 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);
        }
Esempio n. 36
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";
        }
    }
Esempio n. 37
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
        }
Esempio n. 40
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());
                    }
                });
        }