public void homeBtn_Click(object sender, RoutedEventArgs e) { WindowScreen home = (WindowScreen)Window.GetWindow(this); zoomValue = 0.8; zoomLabel.Content = $"{zoomValue * 100}%"; PageImage.Source = null; bottom = 0; //hide TOC & bookmark bookmarkBorder.Visibility = Visibility.Collapsed; TOCBorder.Visibility = Visibility.Collapsed; //clear TOC & bookmark bookmarkList.Clear(); toc.Clear(); file.Close(); if (changeFile) { try { pdfFileBookmark.Save(); } catch (Exception) { MessageBox.Show("Cannot save changes because the file is open in another program", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning); } changeFile = false; } if (pdfFileBookmark != null) { pdfFileBookmark.Close(true); } home.ReturnFromReadingScreen_Click(sender, e); }
private bool EncryptDocument(IFormFile uploadedFile, FileDetail fileDetail, ProcessResult processResult) { try { PdfLoadedDocument document = new PdfLoadedDocument(uploadedFile.OpenReadStream()); //Create a document security. PdfSecurity security = document.Security; //Set user password for the document. security.UserPassword = fileDetail.FilePassword; //Set encryption algorithm. security.Algorithm = PdfEncryptionAlgorithm.AES; //Set key size. security.KeySize = PdfEncryptionKeySize.Key256Bit; using (FileStream outputFileStream = new FileStream($"{fileDetail.FilePath}{fileDetail.FileName}", FileMode.Create)) { document.Save(outputFileStream); document.Close(true); } processResult.processResults.Add( new ProcessResult { IsSuccess = true, Message = "File Successfully saved to local filesystem" }); return(true); } catch (Exception ex) { processResult.processResults.Add( new ProcessResult { IsSuccess = false, Message = ex.Message }); return(false); } }
//Set password for a PDF document public static void SetDocumentPassword(string inputFilePath, string password) { try { Console.WriteLine("Setting password..."); var loadedDocument = new PdfLoadedDocument(inputFilePath); var security = loadedDocument.Security; security.KeySize = Syncfusion.Pdf.Security.PdfEncryptionKeySize.Key256Bit; security.Algorithm = Syncfusion.Pdf.Security.PdfEncryptionAlgorithm.AES; security.UserPassword = password; var inputFileName = Path.GetFileNameWithoutExtension(inputFilePath); var targetFilePath = Path.GetDirectoryName(inputFilePath) + @"\" + inputFileName + "-WithPassword.pdf"; loadedDocument.Save(targetFilePath); loadedDocument.Close(true); Console.WriteLine("Password set and document saved"); } catch { throw; } }
private void FillAndFlatten_Click(object sender, RoutedEventArgs e) { //Get the template PDF form file stream from assembly. Stream documentStream = typeof(FormFilling).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.form_template.pdf"); //Load the PDF document from stream. PdfLoadedDocument document = new PdfLoadedDocument(documentStream); //File the PDF form. FillDocument(document); //Flatten the form fields in a document. if (document.Form != null) { document.Form.Flatten = true; } //Creating the stream object. using (MemoryStream stream = new MemoryStream()) { //Save and close the document. document.Save(stream); document.Close(); stream.Position = 0; //Save the output stream as a file using file picker. PdfUtil.Save("FormFillAndFlatten.pdf", stream); } }
internal string ImageResize(HttpPostedFileBase FileUpload1, int width, int height) { string fileName = FileUpload1.FileName.Replace(" ", ""); UploadedFileName = HttpContext.Current.Server.MapPath("~/images/Thumbnails/" + DateTime.Now.ToShortDateString().Trim().Replace(':', '_').Replace('.', '_') + DateTime.Now.ToShortTimeString().Trim().Replace(':', '_').Replace('.', '_') + fileName + ".png"); PdfLoadedDocument loadedDocument = new PdfLoadedDocument(FileUpload1.InputStream); Bitmap image = loadedDocument.ExportAsImage(0); Bitmap bmp1 = ImageResize(image, width, height); ImageCodecInfo jgpEncoder = GetEncoder(bmp1.RawFormat.Equals(ImageFormat.Png) ? ImageFormat.Png : ImageFormat.Jpeg); System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; EncoderParameters myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L); myEncoderParameter = new EncoderParameter(myEncoder, 100L); myEncoderParameters.Param[0] = myEncoderParameter; using (FileStream stream = File.Create(UploadedFileName)) { bmp1.Save(stream, jgpEncoder, myEncoderParameters); } loadedDocument.Close(true); return("/images/Thumbnails/" + DateTime.Now.ToShortDateString().Trim().Replace(':', '_').Replace('.', '_') + DateTime.Now.ToShortTimeString().Trim().Replace(':', '_').Replace('.', '_') + fileName + ".png"); }
internal Tuple <string, string> ImageResize(HttpPostedFileBase FileUpload1, int width, int height, int bigWidth, int bigHeight) { PdfLoadedDocument loadedDocument = new PdfLoadedDocument(FileUpload1.InputStream); string fileName = FileUpload1.FileName.Replace(" ", ""); UploadedFileName = HttpContext.Current.Server.MapPath("~/images/Upload/" + DateTime.Now.ToShortDateString().Trim().Replace(':', '_').Replace('.', '_') + DateTime.Now.ToShortTimeString().Trim().Replace(':', '_').Replace('.', '_') + fileName + ".png"); Bitmap image = loadedDocument.ExportAsImage(0); Bitmap bmp1 = ImageResize(image, bigWidth, bigHeight); ImageCodecInfo jgpEncoder = GetEncoder(bmp1.RawFormat.Equals(ImageFormat.Png) ? ImageFormat.Png : ImageFormat.Jpeg); System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; EncoderParameters myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L); myEncoderParameter = new EncoderParameter(myEncoder, 100L); myEncoderParameters.Param[0] = myEncoderParameter; using (FileStream stream = File.Create(UploadedFileName)) { bmp1.Save(stream, jgpEncoder, myEncoderParameters); } UploadedFileName = "~/images/Upload/" + UploadedFileName.Split('\\')[UploadedFileName.Split('\\').Length - 1].ToString(); string imageUrlThumbnail = HttpContext.Current.Server.MapPath("~/images/Thumbnails/" + DateTime.Now.ToShortDateString().Trim().Replace(':', '_').Replace('.', '_') + DateTime.Now.ToShortTimeString().Trim().Replace(':', '_').Replace('.', '_') + fileName + ".png"); System.Drawing.Image i = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(UploadedFileName)); System.Drawing.Image thumbnail = new System.Drawing.Bitmap(width, height); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(thumbnail); g.DrawImage(i, 0, 0, width, height); loadedDocument.Close(true); thumbnail.Save(imageUrlThumbnail); return(new Tuple <string, string>("/images/Upload/" + DateTime.Now.ToShortDateString().Trim().Replace(':', '_').Replace('.', '_') + DateTime.Now.ToShortTimeString().Trim().Replace(':', '_').Replace('.', '_') + fileName, "/images/Thumbnails/" + DateTime.Now.ToShortDateString().Trim().Replace(':', '_').Replace('.', '_') + DateTime.Now.ToShortTimeString().Trim().Replace(':', '_').Replace('.', '_') + fileName + ".png")); }
static void Main(string[] args) { //Load the PDF document PdfLoadedDocument loadedDocument = new PdfLoadedDocument("../../../../Data/PDF_Succinctly.pdf"); Dictionary <int, List <RectangleF> > textFound = new Dictionary <int, List <RectangleF> >(); //Find the text in the PDF document loadedDocument.FindText("portable", out textFound); PdfDocument document = new PdfDocument(); //import page based on the find text index foreach (int index in textFound.Keys) { if (textFound[index].Count > 0) { document.ImportPage(loadedDocument, index); } } //save the PDF document document.Save("portable.pdf"); //Close the document document.Close(true); loadedDocument.Close(true); }
private void MergePDF_Click(object sender, RoutedEventArgs e) { //Get template PDF file stream from assembly. if (firstDocumentStream == null) { firstDocumentStream = typeof(MergePDF).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.pdf_succinctly.pdf"); } //Get template PDF file stream from assembly. if (secondDocumentStream == null) { secondDocumentStream = typeof(MergePDF).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.form_template.pdf"); } //Load the PDF document from stream. PdfLoadedDocument loadedDocument = new PdfLoadedDocument(firstDocumentStream); //Load and merge the pdf documents. PdfDocument.Merge(loadedDocument, new PdfLoadedDocument(secondDocumentStream)); //Creating the stream object. using (MemoryStream stream = new MemoryStream()) { //Save and close the document. loadedDocument.Save(stream); loadedDocument.Close(); stream.Position = 0; //Save the output stream as a file using file picker. PdfUtil.Save("MergePDF.pdf", stream); } Dispose(); }
static void Main(string[] args) { // Load an existing PDF PdfLoadedDocument loadedDocument = new PdfLoadedDocument("../../../../../../Data/Invoice.pdf"); TextSearchResultCollection searchCollection; TextSearchItem text = new TextSearchItem("Invoice Number", TextSearchOptions.None); //Search the text from PDF dcoument loadedDocument.FindText(new List <TextSearchItem> { text }, out searchCollection); //Iterate serach collection to get serach results foreach (KeyValuePair <int, MatchedItemCollection> textCollection in searchCollection) { //Get age number Console.WriteLine("Page Number : " + textCollection.Key); foreach (MatchedItem textItem in textCollection.Value) { //Get actual text and bounds Console.WriteLine("Text :" + textItem.Text); Console.WriteLine("Text bounds :" + textItem.Bounds); } } //Close the document loadedDocument.Close(true); }
private void button1_Click(object sender, RoutedEventArgs e) { Stream documentStream; string fileName = string.Empty; if ((bool)import.IsChecked) { //Get the import template PDF file stream from assembly. documentStream = typeof(ImportAndExport).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.form_template.pdf"); fileName = "ImportForm_Template.pdf"; } else { //Get the export template PDF file stream from assembly. documentStream = typeof(ImportAndExport).GetTypeInfo().Assembly.GetManifestResourceStream("syncfusion.pdfdemos.winui.Assets.export_template.pdf"); fileName = "ExportForm_Template.pdf"; } //Load the PDF document from stream. PdfLoadedDocument loadedDocument = new PdfLoadedDocument(documentStream); //Creating the stream object. using (MemoryStream stream = new MemoryStream()) { //Save and close the document. loadedDocument.Save(stream); loadedDocument.Close(); stream.Position = 0; //Save the output stream as a file using file picker. PdfUtil.Save(fileName, stream); } }
public List <string> LoadDocument(string fileName) { List <string> parsedSchedule = new List <string>(); //Load the PDF document. FileStream docStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); //Load the PDF document. PdfLoadedDocument loadedDocument = new PdfLoadedDocument(docStream); // Loading page collections PdfLoadedPageCollection loadedPages = loadedDocument.Pages; string extractedText = string.Empty; // Extract text from existing PDF document pages foreach (PdfLoadedPage loadedPage in loadedPages) { extractedText += loadedPage.ExtractText(); } //Close the document. loadedDocument.Close(true); docStream.Close(); parsedSchedule.AddRange(extractedText.Split("\r\n")); return(parsedSchedule); }
void OnButtonClicked(object sender, EventArgs e) { Stream docStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.Syncfusion_Windows8_whitepaper.pdf"); PdfLoadedDocument ldoc = new PdfLoadedDocument(docStream); PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 100f, PdfFontStyle.Regular); foreach (PdfPageBase lPage in ldoc.Pages) { PdfGraphics g = lPage.Graphics; PdfGraphicsState state = g.Save(); g.SetTransparency(0.25f); g.TranslateTransform(50, lPage.Size.Height / 2 ); g.RotateTransform(-40); g.DrawString("Syncfusion", font, PdfPens.Red, PdfBrushes.Red, new PointF(0,0)); } MemoryStream stream = new MemoryStream(); ldoc.Save(stream); ldoc.Close(true); if (Device.OS == TargetPlatform.WinPhone || Device.OS == TargetPlatform.Windows) Xamarin.Forms.DependencyService.Get<ISaveWindowsPhone>().Save("Stamping.pdf", "application/pdf", stream); else Xamarin.Forms.DependencyService.Get<ISave>().Save("Stamping.pdf", "application/pdf", stream); }
public static bool MarkPdf(string inputFileName, string outputFileName, int jobNo, int jtsk, string userName, int qty = 0, string notes = "") { using (PdfLoadedDocument ldoc = new PdfLoadedDocument(inputFileName)) { foreach (PdfPageBase page in ldoc.Pages) { //PdfPageBase page = ldoc.Pages[0]; PdfGraphics gra = page.Graphics; SizeF pgSize = page.Size; string qtyText = ""; if (qty > 0) { qtyText = "- TOTAL QTY : {qty} "; } gra.DrawString($"JOB :{jobNo} | JTSK : {jtsk} ISSUED BY : {userName}", font, PdfBrushes.Blue, 10, pgSize.Height - 10, new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Bottom)); gra.DrawString($"ISSUE DATE :{DateTime.Now:d} {qtyText}{notes}", font, PdfBrushes.Blue, 10, pgSize.Height - 20, new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Bottom)); } ldoc.Save(outputFileName); ldoc.Close(true); return(true); } }
static void Main(string[] args) { //Load the PDF document PdfLoadedDocument loadedDocument = new PdfLoadedDocument("../../../../../../Data/Invoice.pdf"); //Search total amount string regexPattern = @"(TOTAL)([-+]?[0-9]*\.?[0-9]+)"; // See the complete regular expressions reference at https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx // Extract all the text from existing PDF document pages foreach (PdfLoadedPage loadedPage in loadedDocument.Pages) { TextLines lines; loadedPage.ExtractText(out lines); foreach (TextLine line in lines) { Regex re = new Regex(regexPattern, RegexOptions.IgnoreCase); Match match = re.Match(line.Text); if (match.Success) { //Print the total amount Console.WriteLine("Found Total Amount Number:" + match.Value.Replace("Total", "")); } } } //Close the document loadedDocument.Close(true); }
void OnButtonClicked(object sender, EventArgs e) { Stream docStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.Syncfusion_Windows8_whitepaper.pdf"); PdfLoadedDocument ldoc = new PdfLoadedDocument(docStream); PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 100f, PdfFontStyle.Regular); foreach (PdfPageBase lPage in ldoc.Pages) { PdfGraphics g = lPage.Graphics; PdfGraphicsState state = g.Save(); g.SetTransparency(0.25f); g.TranslateTransform(50, lPage.Size.Height / 2); g.RotateTransform(-40); g.DrawString("Syncfusion", font, PdfPens.Red, PdfBrushes.Red, new PointF(0, 0)); g.Restore(state); } MemoryStream stream = new MemoryStream(); ldoc.Save(stream); ldoc.Close(true); if (Device.OS == TargetPlatform.WinPhone || Device.OS == TargetPlatform.Windows) { Xamarin.Forms.DependencyService.Get <ISaveWindowsPhone>().Save("Stamping.pdf", "application/pdf", stream); } else { Xamarin.Forms.DependencyService.Get <ISave>().Save("Stamping.pdf", "application/pdf", stream); } }
public override void Init(object initData) { base.Init(initData); if (initData is byte[]) { PdfDocumentStream = new MemoryStream(initData as byte[]); } else if (initData is Tuple <byte[], int> ) { PdfLoadedDocument loadedDocument = new PdfLoadedDocument(((Tuple <byte[], int>)initData).Item1); PdfDocument document = new PdfDocument(); int startIndex = 0; int endIndex = ((Tuple <byte[], int>)initData).Item2 - 1; endIndex = Math.Min(loadedDocument.Pages.Count, endIndex); //Import all the pages to the new PDF document. document.ImportPageRange(loadedDocument, startIndex, endIndex); var _stream = new MemoryStream(); document.Save(_stream); loadedDocument.Close(); document.Close(); PdfDocumentStream = _stream; } }
//Remove password from password protected PDF file public static void RemoveDocumentPassword(string inputFilePath, string password) { try { Console.WriteLine("Removing password..."); var loadedDocument = new PdfLoadedDocument(inputFilePath, password); loadedDocument.Security.UserPassword = string.Empty; var inputFileName = Path.GetFileNameWithoutExtension(inputFilePath); var targetFilePath = Path.GetDirectoryName(inputFilePath) + @"\" + inputFileName + "-WithoutPassword.pdf"; loadedDocument.Save(targetFilePath); loadedDocument.Close(true); Console.WriteLine("Password removed and document saved"); } catch (PdfDocumentException) { throw; } catch (Exception) { throw; } }
void OnButtonClicked(object sender, EventArgs e) { Stream docStream = typeof(Stamping).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.Product Catalog.pdf"); PdfLoadedDocument ldoc = new PdfLoadedDocument(docStream); PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 100f, PdfFontStyle.Regular); foreach (PdfPageBase lPage in ldoc.Pages) { PdfGraphics g = lPage.Graphics; PdfGraphicsState state = g.Save(); g.TranslateTransform(ldoc.Pages[0].Size.Width / 2, ldoc.Pages[0].Size.Height / 2); g.SetTransparency(0.25f); SizeF waterMarkSize = font.MeasureString("Sample"); g.RotateTransform(-40); g.DrawString("Sample", font, PdfPens.Red, PdfBrushes.Red, new PointF(-waterMarkSize.Width / 2, -waterMarkSize.Height / 2)); g.Restore(state); } MemoryStream stream = new MemoryStream(); ldoc.Save(stream); ldoc.Close(true); if (stream != null) { SaveAndroid androidSave = new SaveAndroid(); androidSave.Save("Stamping.pdf", "application/pdf", stream, m_context); } }
static void Main(string[] args) { //Load the PDF document PdfLoadedDocument loadedDocument = new PdfLoadedDocument("../../../../../../Data/Invoice.pdf"); // Get the first page of the loaded PDF document PdfPageBase page = loadedDocument.Pages[0]; TextLines lineCollection = new TextLines(); // Extract text from the first page with bounds page.ExtractText(out lineCollection); RectangleF textBounds = new RectangleF(474, 161, 50, 9); string invoiceNumer = ""; //Get the text provided in the bounds foreach (TextLine txtLine in lineCollection) { foreach (TextWord word in txtLine.WordCollection) { if (textBounds.IntersectsWith(word.Bounds)) { invoiceNumer = word.Text; break; } } } //Close the PDF document loadedDocument.Close(true); File.WriteAllText("data.txt", invoiceNumer); }
/// <summary> /// Export to PDF on Button click /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Exportbutton_Click(object sender, EventArgs e) { var converter = new GridPDFConverter(); var lowest = 0; //Adding PageBreaks to a list. var rows = new List <int> { 30, 63, 90, 130, 150 }; var pdfDocument = new PdfDocument(); pdfDocument.Save("Sample.pdf"); foreach (var rownumber in rows) { var pdf = new PdfDocument(); var maximumRow = rownumber; converter.ExportToPdf(pdf, gridControl1, GridRangeInfo.Rows(lowest, maximumRow)); var stream = new MemoryStream(); pdf.Save(stream); var loadedDocument = new PdfLoadedDocument("Sample.pdf"); loadedDocument = PdfDocumentBase.Merge(loadedDocument, new PdfLoadedDocument(stream)) as PdfLoadedDocument; loadedDocument.Save("Sample.pdf"); loadedDocument.Close(true); stream.Dispose(); lowest = maximumRow + 1; } var loadedDocument1 = new PdfLoadedDocument("Sample.pdf"); loadedDocument1.Pages.RemoveAt(0); loadedDocument1.Save("Sample.pdf"); Process.Start("Sample.pdf"); }
private void button3_Click(object sender, RoutedEventArgs e) { if (documentStream == null) { documentStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.Essential_Studio.pdf"); } //Load the selected PDF document. PdfLoadedDocument loadedDocument = new PdfLoadedDocument(documentStream); //Get the .pfx certificate file stream. if (certificateStream == null) { certificateStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.PDF.pfx"); } //Create PdfCertificate using certificate stream and password. PdfCertificate pdfCert = new PdfCertificate(certificateStream, txtOwnerPassword.Password); //Add certificate to document first page. PdfSignature signature = new PdfSignature(loadedDocument, loadedDocument.Pages[0], pdfCert, "Signature"); signature.Bounds = new System.Drawing.RectangleF(5, 5, 300, 300); MemoryStream stream = new MemoryStream(); loadedDocument.Save(stream); loadedDocument.Close(true); SaveFile(stream, "output.PDF"); }
static void Main(string[] args) { //Initialize OCR processor OCRProcessor processor = new OCRProcessor(@"../../../../../../Data/TesseractBinaries/3.02/"); //Load a PDF document PdfLoadedDocument lDoc = new PdfLoadedDocument("../../../../../../Data/Invoice_scanned.pdf"); //Set OCR language to process processor.Settings.Language = Languages.English; OCRLayoutResult hocrBounds; processor.PerformOCR(lDoc, @"../../../../../../Data/Tessdata/", out hocrBounds); StreamWriter writer = new StreamWriter("data.txt"); foreach (Page pages in hocrBounds.Pages) { foreach (Line line in pages.Lines) { writer.WriteLine(line.Text); } } writer.Close(); lDoc.Close(true); processor.Dispose(); }
void OnButtonClicked(object sender, EventArgs e) { Stream docStream = typeof(Booklet).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.SalesOrderDetail.pdf"); //Load the PDF document into the loaded document object. PdfLoadedDocument loadedDocument = new PdfLoadedDocument(docStream); //Get the certificate stream from .pfx file. Stream certificateStream = typeof(DigitalSignature).GetTypeInfo().Assembly.GetManifestResourceStream("SampleBrowser.Samples.PDF.Assets.PDF.pfx"); //Create PdfCertificate using certificate stream and password. PdfCertificate pdfCert = new PdfCertificate(certificateStream, "password123"); //Add certificate to document first page. PdfSignature signature = new PdfSignature(loadedDocument, loadedDocument.Pages[0], pdfCert, "Signature"); signature.Bounds = new Syncfusion.Drawing.RectangleF(5, 5, 300, 300); MemoryStream stream = new MemoryStream(); //Save the PDF document loadedDocument.Save(stream); //Close the PDF document loadedDocument.Close(true); if (stream != null) { stream.Position = 0; ComposeMail("DigitalSignature.pdf", null, "Signing the document", "Syncfusion", stream); } }
public void MergePDF() { //Loads document PdfLoadedDocument combinePDF = new PdfLoadedDocument(workPath + pdfFileName); PdfDocument newPDF = new PdfDocument(); //Imports the page at 1 from the lDoc foreach (int pageNum in pages) { newPDF.ImportPage(combinePDF, pageNum - 1); } //Saves the document newPDF.Save("new.pdf"); //Closes the document newPDF.Close(true); combinePDF.Close(true); }
private void btnSplitPDF_Click(object sender, System.EventArgs e) { PdfImageInfo[] imagesInfo = ldoc.Pages[0].ImagesInfo; foreach (PdfImageInfo imgInfo in imagesInfo) { //Removing Image ldoc.Pages[0].RemoveImage(imgInfo); } ldoc.Save("RemoveImage.pdf"); ldoc.Close(); //Message box confirmation to view the created PDF document. if (MessageBox.Show("Do you want to view the PDF file?", "PDF File Created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { //Launching the PDF file using the default Application.[Acrobat Reader] #if NETCORE System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo = new System.Diagnostics.ProcessStartInfo("RemoveImage.pdf") { UseShellExecute = true }; process.Start(); #else System.Diagnostics.Process.Start("RemoveImage.pdf"); #endif this.Close(); } else { // Exit this.Close(); } }
//Change password for a PDF document public static void ChangeDocumentPassword(string inputFilePath, string existingPassword, string newPassword) { try { Console.WriteLine("Changing document password..."); var loadedDocument = new PdfLoadedDocument(inputFilePath, existingPassword); loadedDocument.Security.UserPassword = newPassword; var inputFileName = Path.GetFileNameWithoutExtension(inputFilePath); var targetFilePath = Path.GetDirectoryName(inputFilePath) + @"\" + inputFileName + "-WithNewPassword.pdf"; loadedDocument.Save(targetFilePath); loadedDocument.Close(true); Console.WriteLine("Password changed and document saved"); } catch (PdfDocumentException) { throw; } catch (Exception) { throw; } }
private async void Button_Click_1(object sender, RoutedEventArgs e) { Stream docStream = typeof(StampDocument).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.Essential_Studio.pdf"); PdfLoadedDocument ldoc = new PdfLoadedDocument(docStream); PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 36f); foreach (PdfPageBase lPage in ldoc.Pages) { PdfGraphics g = lPage.Graphics; PdfGraphicsState state = g.Save(); g.SetTransparency(0.25f); g.RotateTransform(-40); g.DrawString(stampText.Text, font, PdfPens.Red, PdfBrushes.Red, new PointF(-150, 450)); if (imagewatermark.IsChecked.Value) { Stream imagestream = typeof(StampDocument).GetTypeInfo().Assembly.GetManifestResourceStream("Syncfusion.SampleBrowser.UWP.Pdf.Pdf.Assets.Ani.gif"); PdfImage image = new PdfBitmap(imagestream); g.Restore(state); g.SetTransparency(0.25f); g.DrawImage(image, 0, 0, lPage.Graphics.ClientSize.Width, lPage.Graphics.ClientSize.Height); imagestream.Dispose(); } } MemoryStream stream = new MemoryStream(); await ldoc.SaveAsync(stream); ldoc.Close(true); Save(stream, "StampDocument.pdf"); docStream.Dispose(); }
public ActionResult RearrangePages(string Browser, string submit1) { string basePath = _hostingEnvironment.WebRootPath; string dataPath = string.Empty; dataPath = basePath + @"/PDF/"; if (submit1 == "View Template") { Stream file2 = new FileStream(dataPath + "SyncfusionBrochure.pdf", FileMode.Open, FileAccess.Read, FileShare.Read); //Load the template document PdfLoadedDocument loadedDocument = new PdfLoadedDocument(file2); //Save the PDF to the MemoryStream MemoryStream ms = new MemoryStream(); loadedDocument.Save(ms); //If the position is not set to '0' then the PDF will be empty. ms.Position = 0; //Close the PDF document. loadedDocument.Close(true); //Download the PDF document in the browser. FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf"); fileStreamResult.FileDownloadName = "InputTemplate.pdf"; return(fileStreamResult); } else { //Read the file FileStream file = new FileStream(dataPath + "SyncfusionBrochure.pdf", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //Load the input PDF document PdfLoadedDocument ldoc = new PdfLoadedDocument(file); //Rearrange the page by index ldoc.Pages.ReArrange(new int[] { 2, 0, 1 }); //Save the PDF to the MemoryStream MemoryStream ms = new MemoryStream(); ldoc.Save(ms); //If the position is not set to '0' then the PDF will be empty. ms.Position = 0; //Close the PDF document. ldoc.Close(true); //Download the PDF document in the browser. FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf"); fileStreamResult.FileDownloadName = "RearrangedPages.pdf"; return(fileStreamResult); } }
static void Main(string[] args) { //Load PDF document PdfLoadedDocument document = new PdfLoadedDocument("../../../../Data/PDF_Succinctly.pdf"); //Split PDF document with pattern document.Split("Document-{0}.pdf", ); //Close the document document.Close(true); }
public async Task <FileParseResult> ParseFile(string remoteFile) { FileParseResult parseResult = new FileParseResult(); PoolSchedule poolSchedule = new PoolSchedule(); poolSchedule.Link = remoteFile; parseResult.Success = true; parseResult.Schedule = poolSchedule; string extractedText = string.Empty; try { HttpClient httpClient = new HttpClient(); HttpResponseMessage httpResponseMessage = await httpClient.GetAsync(remoteFile); if (httpResponseMessage.IsSuccessStatusCode) { Stream contentStream = await httpResponseMessage.Content.ReadAsStreamAsync(); PdfLoadedDocument loadedDocument = new PdfLoadedDocument(contentStream); DateTime modyficationDate = loadedDocument.DocumentInformation.ModificationDate; poolSchedule.ModificationDate = modyficationDate; // Loading page collections PdfLoadedPageCollection loadedPages = loadedDocument.Pages; extractedText = loadedPages[0].ExtractText(); //Close the document. loadedDocument.Close(true); List <string> pdfList = new List <string>(); pdfList.AddRange(extractedText.Split("\r\n")); string header = pdfList.Where(s => s.StartsWith("Harmonogram")).SingleOrDefault(); if (header != null) //checking if the header is compatible with the schema { int linkLenght = header.Length; int fromIndex = header.IndexOf("od"); string dates = header.Substring(fromIndex, (linkLenght - fromIndex)); string startDateString = dates.Substring(2, dates.IndexOf("do") - 2).Trim(); string endDateString = dates.Substring(dates.IndexOf("do") + 2, dates.Length - 4 - (dates.IndexOf("do") + 2)).Trim(); GetValuesFromDateString(startDateString, poolSchedule, DateType.From); GetValuesFromDateString(endDateString, poolSchedule, DateType.To); } } poolSchedule.CheckDates(); httpResponseMessage.Dispose(); httpClient.Dispose(); return(parseResult); } catch (Exception ex) { logger.LogError(ex, "Błąd podczas parsowania pliku PDF"); parseResult.Success = false; parseResult.Schedule = null; } return(parseResult); }
public static void AssinarDocumento() { var arquivoEnt = $"d:\\temp\\modelo.pdf"; var pdf = DSHelper.ReadContent(arquivoEnt); var arquivo = $"d:\\temp\\modeloOut.pdf"; float x; float y; Stream pfxStream = File.OpenRead("MRV ENGENHARIA E PARTICIPAÇÕES S.A..pfx"); //Creates a certificate instance from PFX file with private key. PdfCertificate pdfCert = new PdfCertificate(pfxStream, "zzzzz"); PdfLoadedDocument loadedDocument = new PdfLoadedDocument(pdf); var lista = new Dictionary <int, List <Syncfusion.Drawing.RectangleF> >(); loadedDocument.FindText("Assinado:", out lista); foreach (var item in lista) { x = item.Value[0].X + 100; y = item.Value[0].Y; var page = loadedDocument.Pages[item.Key] as PdfLoadedPage; //aplica logo da assinatura em todas as paginas if (page != null) { Stream seloStream = File.OpenRead("SeloMrv.jpg"); PdfBitmap signatureImage = new PdfBitmap(seloStream); PdfGraphics gfx = page.Graphics; gfx.DrawImage(signatureImage, x, y, 90, 80); } //Applica o certificado somente na ultima pagina if (item.Value == lista[lista.Keys.Count - 1]) { //Creates a signature field. PdfSignatureField signatureField = new PdfSignatureField(page, "AssinaturaMRV"); signatureField.Bounds = new Syncfusion.Drawing.RectangleF(x, item.Value[0].Y, 50, 50); signatureField.Signature = new PdfSignature(page, "MRV Engenharia"); //Adds certificate to the signature field. signatureField.Signature.Certificate = pdfCert; signatureField.Signature.Reason = "Assinado pela MRV Engenharia"; //Adds the field. loadedDocument.Form.Fields.Add(signatureField); } } //Saves the certified PDF document. using (FileStream fileOut = new FileStream(arquivo, FileMode.Create)) { loadedDocument.Save(fileOut); loadedDocument.Close(true); } //return arquivo; }