/// <summary> /// Main method for running the sample. /// </summary> public static SampleOutputInfo[] Run(Stream input) { PdfFile file = new PdfFile(input); PdfPageContent[] content = file.ExtractPageContent(0, file.PageCount - 1); file = null; PdfFixedDocument document = new PdfFixedDocument(); PdfPage page1 = document.Pages.Add(); // Draw the same page content 4 times on the new page, the content is scaled to half and flipped. page1.Graphics.DrawFormXObject(content[0], 0, 0, page1.Width / 2, page1.Height / 2); page1.Graphics.DrawFormXObject(content[0], page1.Width / 2, 0, page1.Width / 2, page1.Height / 2, 0, PdfFlipDirection.VerticalFlip); page1.Graphics.DrawFormXObject(content[0], 0, page1.Height / 2, page1.Width / 2, page1.Height / 2, 0, PdfFlipDirection.HorizontalFlip); page1.Graphics.DrawFormXObject(content[0], page1.Width / 2, page1.Height / 2, page1.Width / 2, page1.Height / 2, 0, PdfFlipDirection.VerticalFlip | PdfFlipDirection.HorizontalFlip); PdfPage page2 = document.Pages.Add(); // Draw 3 pages on the new page. page2.Graphics.DrawFormXObject(content[0], 0, 0, page2.Width / 2, page2.Height / 2); page2.Graphics.DrawFormXObject(content[1], page2.Width / 2, 0, page2.Width / 2, page2.Height / 2); page2.Graphics.DrawFormXObject(content[2], 0, page2.Height, page2.Height / 2, page2.Width, 90); SampleOutputInfo[] output = new SampleOutputInfo[] { new SampleOutputInfo(document, "xfinium.pdf.sample.pageimposition.pdf") }; return output; }
[TestCase("testcase77.pdf", -3900)] //AES128 -no-edit -no-copy -no-annot -no-forms -no-extract -no-assemble -no-hq-print public void PDFPermissions(string PDF, long pValue) { string errorMsg = string.Empty; string filePath = Path.Combine(TestHelper.DataFolder, PDF); Assert.IsTrue(File.Exists(filePath)); PdfFile pdfFile = new PdfFile(filePath); pdfFile.Open(ref errorMsg); Assert.IsTrue(string.IsNullOrEmpty(errorMsg)); Assert.AreEqual(pdfFile.EncryptionRecordInfo.pValue, pValue); }
public void MetadataEncryption(string PDF, bool metadataIsEncrypted) { string errorMsg = string.Empty; string filePath = Path.Combine(TestHelper.DataFolder, PDF); Assert.IsTrue(File.Exists(filePath)); PdfFile pdfFile = new PdfFile(filePath); pdfFile.Open(ref errorMsg); Assert.IsTrue(string.IsNullOrEmpty(errorMsg)); Assert.AreEqual(pdfFile.EncryptionRecordInfo.metadataIsEncrypted, metadataIsEncrypted); }
public async Task <IActionResult> OnPost() { if (ModelState.IsValid) { #region files code if (PdfFile != null || ImgFile != null) { if (PdfFile != null) { #region pdf file string pdfFileName = Guid.NewGuid().ToString() + Path.GetFileName(PdfFile.FileName); string pdfFilePath = Path.Combine(env.WebRootPath, "files"); string fullPath = Path.Combine(pdfFilePath, pdfFileName); Book.Url = pdfFileName; await PdfFile.CopyToAsync(new FileStream(fullPath, FileMode.Create)); #endregion } if (ImgFile != null) { #region img file string imgFileName = Guid.NewGuid().ToString() + Path.GetFileName(ImgFile.FileName); string imgFilePath = Path.Combine(env.WebRootPath, "imgs"); string imgFullPath = Path.Combine(imgFilePath, imgFileName); Book.ImgUrl = imgFileName; await ImgFile.CopyToAsync(new FileStream(imgFullPath, FileMode.Create)); #endregion } } #endregion var oldBook = await db.Books.FirstOrDefaultAsync(b => b.Id == id); if (oldBook == null) { return(NotFound()); } oldBook.Name = Book.Name; oldBook.Auther = Book.Auther; oldBook.CategoryId = Book.CategoryId; oldBook.LangCategoryId = Book.LangCategoryId; oldBook.Description = Book.Description; db.Entry(oldBook).State = EntityState.Modified; await db.SaveChangesAsync(); return(RedirectToPage("index")); } return(Page()); }
public static void SplitPage() { PdfFile pdfFile = new PdfFile(); PdfDocument document = pdfFile.Import(File.ReadAllBytes("sample.pdf")); //Split each page to a new Pdf document List <PdfDocument> splitDocuments = document.Split(); for (int i = 0; i < splitDocuments.Count; i++) { PdfDocument split = splitDocuments[i]; File.WriteAllBytes(String.Format("Split-page{0}.pdf", i + 1), pdfFile.Export(split)); } }
public static void ReadAndModifyFormField() { PdfFile pdfFile = new PdfFile(); PdfDocument document = pdfFile.Import(File.ReadAllBytes("CreateFormField.pdf")); foreach (FormField field in document.AcroForm.FormFields) { switch (field.FieldType) { case FormFieldType.CheckBox: if (field.Name == "checkBox1") { ((CheckBoxField)field).IsChecked = false; } break; case FormFieldType.ComboBox: if (field.Name == "comboBox1") { ((ComboBoxField)field).Value = ((ComboBoxField)field).Options[0]; } break; case FormFieldType.ListBox: if (field.Name == "listBox1") { ((ListBoxField)field).Value = new ChoiceOption[] { ((ListBoxField)field).Options[0] } } ; break; case FormFieldType.RadioButton: if (field.Name == "radioButton1") { ((RadioButtonField)field).Value = ((RadioButtonField)field).Options[0]; } break; case FormFieldType.TextBox: if (field.Name == "textBox1") { ((TextBoxField)field).Value = "new text"; } break; } } File.WriteAllBytes("ModifyFormField.pdf", pdfFile.Export(document)); }
public static void AddTextSignature2PDF() { PdfFile pdfFile = new PdfFile(); PdfDocument document = pdfFile.Import(File.ReadAllBytes("sample.pdf")); //Input your certificate and password X509Certificate2 certificate = new X509Certificate2("test.pfx", "iditect"); //First you need create a SignatureField with unique name SignatureField signatureField = new SignatureField("iDiTect Sign Field"); //Add signature object to a signature field, so we can add a visualization to it signatureField.Signature = new Signature(certificate); //Add signature info as need signatureField.Signature.Properties.Reason = "Sign by iDiTect"; signatureField.Signature.Properties.Location = "World Wide Web"; signatureField.Signature.Properties.ContactInfo = "1234567"; //Apply a visible signature widiget to represent the contents of the signature field. SignatureWidget widget = signatureField.Widgets.AddWidget(); //Set signature position and size widget.Rect = new System.Windows.Rect(new System.Windows.Point(200, 200), new System.Windows.Size(400, 100)); widget.RecalculateContent(); //Customize signature appearance, you can show all signature info, or just name or date PageContentBuilder signatureAppearance = new PageContentBuilder(widget.Content.NormalContentSource); signatureAppearance.Position.Translate(10, 0); signatureAppearance.DrawText("Digitally signed by " + certificate.GetNameInfo(X509NameType.SimpleName, true)); signatureAppearance.Position.Translate(10, 20); signatureAppearance.DrawText("Reason: " + signatureField.Signature.Properties.Reason); signatureAppearance.Position.Translate(10, 40); signatureAppearance.DrawText("Location: " + signatureField.Signature.Properties.Location); signatureAppearance.Position.Translate(10, 60); signatureAppearance.DrawText("Contact: " + signatureField.Signature.Properties.ContactInfo); signatureAppearance.Position.Translate(10, 80); signatureAppearance.DrawText("Date: " + DateTime.Now.ToString()); //Add this signature to first PDF page document.Pages[0].Annotations.Add(widget); document.AcroForm.FormFields.Add(signatureField); //Digital sign feature need the stream support reading, so you have to use ReadWrite mode here using (FileStream fs = new FileStream("signed.pdf", FileMode.Create, FileAccess.ReadWrite)) { pdfFile.Export(document, fs); } }
public static void ReadOneBarcodeTypeFromOnePdfPage() { PdfFile pdf = new PdfFile("test.pdf"); pdf.SetDPI = 72; Image pageImage = pdf.ConvertToImage(0, 1000, 1000); Bitmap bitmap = new Bitmap(pageImage); string[] data = PdfBarcodeReader.Recognize(bitmap, PdfBarcodeReader.Code128); foreach (string result in data) { Console.WriteLine(result); } Console.ReadKey(); }
private async Task DisplayPdf(PdfFile pdf) { PdfDocument pdfDocument = null; if (pdf != null) { pdfDocument = await PdfDocument.LoadFromFileAsync(pdf.File); } await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { await pdfViewer.DisplayPdfDoc(pdfDocument); }); }
public void Transform_Uses_FileListTransformer_Transform_With_Source_PdfFile() { var source = new FileList(); var pdfFiles = new List <PdfFile>(); var pdfFile = new PdfFile(); pdfFiles.Add(pdfFile); source.PdfFiles = pdfFiles; var pdfFileTransformer = new Mock <ITransformer <PdfFile, PdfFileDto> >(); var sut = CreateSut(pdfFileTransformer.Object); sut.Transform(source); pdfFileTransformer.Verify(q => q.Transform(pdfFile), Times.Once()); }
public static void AddTable() { PdfDocument document = new PdfDocument(); PdfPage page = document.Pages.AddPage(); PageContentBuilder builder = new PageContentBuilder(page); builder.Position.Translate(50, 50); Table table = CreateSimpleTable(); table.LayoutType = TableLayoutType.FixedWidth; builder.DrawTable(table, 500); PdfFile pdfFile = new PdfFile(); File.WriteAllBytes("AddTable.pdf", pdfFile.Export(document)); }
private string GetFileContents(PdfFile file) { using (var ms = new MemoryStream()) { var sb = new StringBuilder(); file.Save(ms); ms.Seek(0, SeekOrigin.Begin); int b; while ((b = ms.ReadByte()) >= 0) { sb.Append((char)b); } return(sb.ToString()); } }
// Mail Management // Header public void BRDHeader(PdfFile file, Document doc, PdfWriter writer, Departure Departure) { file.CreateParagraph(doc, "ROYAUM DU MAROC\nMINISTERE DE LA SANTE\nnDELEGATION TANGER ASSILAH\nHOPITAL MOHAMED VI", false, false, false); file.AddImage(doc, 50f, 100f, 10f, doc.PageSize.Width / 2 - 15, doc.PageSize.Height / 2 + 320, Resources.MarocHeaderresx.Maroc, ImageFormat.Bmp); file.CreateText(doc, writer, "LE MEDECIN DIRECTEUR DE L'HOPITAL", doc.PageSize.Width / 2 - 85, doc.PageSize.Height / 2 + 250, false, true); file.CreateText(doc, writer, "MOHAMMED VI", doc.PageSize.Width / 2 - 15, doc.PageSize.Height / 2 + 230, false, true); file.CreateText(doc, writer, "Tanger", doc.PageSize.Width / 2 + 5, doc.PageSize.Height / 2 + 210, false, true); file.CreateText(doc, writer, Departure.Configuration.Adress.ToString(), doc.PageSize.Width / 2 - 2, doc.PageSize.Height / 2 + 170, false, true); file.CreateText(doc, writer, "BORDERAU D'ENVOI", doc.PageSize.Width / 2 - 35, doc.PageSize.Height / 2 + 130, true, false); //} }
public static void AddTable(DataTable dt) { PdfDocument document = new PdfDocument(); PdfPage page = document.Pages.AddPage(); PageContentBuilder builder = new PageContentBuilder(page); builder.Position.Translate(50, 50); Table table = CreateSimpleTable(dt); table.LayoutType = TableLayoutType.FixedWidth; builder.DrawTable(table); PdfFile pdfFile = new PdfFile(); File.WriteAllBytes("Reporte_Alumnos_" + DateTime.Now.ToString("dd_MM_yyyy_HH_mm_ss") + ".pdf", pdfFile.Export(document)); }
private void StartStopButton_Click(object sender, EventArgs e) { startStopButton.Enabled = false; if (startStopButton.Text.Equals("Aufteilen starten")) { selectFileButton.Enabled = false; settingsButton.Enabled = false; filePathTextBox.Enabled = false; pdf = new PdfFile(filePathTextBox.Text); pdf.StartSplitting(); } else { pdf.StopSplitting(); } }
public bool CreatePdf(PdfFile pdf) { log.Info("[start CreatePdf]"); try { StringBuilder query = new StringBuilder(); query.AppendFormat(@" insert into {0} ( [pdf_guid] ,[pdf_name] ,[pdf_desc] ,[pdf_lang] ) values ( @pdfGuid, @pdfName, @pdfDesc, @pdfLang ) " , TableMapping.TBL_PDF ); List <SqlParameter> parameters = new List <SqlParameter>(); parameters.Add(CreateParameter("@pdfGuid", SqlDbType.VarChar, pdf.PdfGuid, 300)); parameters.Add(CreateParameter("@pdfName", SqlDbType.VarChar, pdf.PdfName, 150)); parameters.Add(CreateParameter("@pdfDesc", SqlDbType.VarChar, pdf.PdfDescription, 100)); parameters.Add(CreateParameter("@pdfLang", SqlDbType.VarChar, pdf.PdfLanguage, 2)); DBConnect(); bool result = CreateUpdateDelete(query.ToString(), parameters) > 0; DBDisconnect(); return(result); } catch (Exception e) { log.ErrorFormat("Repository Error {0}", e.ToString()); throw; } }
public static void AddImage() { PdfFile pdfFile = new PdfFile(); PdfDocument document; using (FileStream fs = File.OpenRead("sample.pdf")) { //Read pdf document from stream document = pdfFile.Import(fs); } //Get first page of pdf PdfPage page = document.Pages[0]; //Create page level builder PageContentBuilder builder = new PageContentBuilder(page); //Add image using builder's DrawImage directly using (Stream imgStream = File.OpenRead("sample.jpg")) { //Set image position builder.Position.Translate(100, 100); //insert image as original size builder.DrawImage(imgStream); //insert image with customized size //builder.DrawImage(imgStream, new Size(80, 80)); } //Add image using Block object using (Stream imgStream = File.OpenRead("sample2.jpg")) { //Set image position builder.Position.Translate(100, 400); Block block = new Block(); //insert image as original size //block.InsertImage(imgStream); //insert image with customized size block.InsertImage(imgStream, new Size(100, 100)); builder.DrawBlock(block); } using (FileStream fs = File.OpenWrite("InsertImage.pdf")) { pdfFile.Export(document, fs); } }
/* ----------------------------------------------------------------- */ /// /// GetUserPassword /// /// <summary> /// Gets the user password from the specified arguments. /// </summary> /// /// <param name="src">PdfReader object.</param> /// <param name="file">PDF file information.</param> /// /// <returns>User password.</returns> /// /// <remarks> /// 暗号化方式が AES256 の場合、ユーザパスワードの解析に /// 失敗するので除外しています。AES256 の場合の解析方法を要検討。 /// </remarks> /// /* ----------------------------------------------------------------- */ public static string GetUserPassword(this PdfReader src, PdfFile file) { if (file.FullAccess) { var method = src.GetEncryptionMethod(); if (method == EncryptionMethod.Aes256) { return(string.Empty); // see remarks } var bytes = src.ComputeUserPassword(); if (bytes?.Length > 0) { return(Encoding.UTF8.GetString(bytes)); } } return(file.Password); }
public void VerifyFontsAreAddedOnSaveTest() { var file = new PdfFile(); var page = PdfPage.NewLetter(); var text = new PdfText("foo", new PdfFontType1(PdfFontType1Type.Helvetica), PdfMeasurement.Points(12.0), new PdfPoint()); page.Items.Add(text); file.Pages.Add(page); Assert.Equal(0, file.Fonts.Count); using (var ms = new MemoryStream()) { file.Save(ms); } Assert.True(ReferenceEquals(text.Font, file.Fonts.Single())); }
public void AddPdfAsyncTest() { var files = Directory.EnumerateFiles(Environment.CurrentDirectory); var pdfs = files.Where(n => Path.GetExtension(n).ToLower() == ".pdf"); Assert.IsTrue(pdfs.Any()); foreach (var item in pdfs) { PdfFile pdf = new PdfFile(item); var savePath = Path.Combine(storePath, pdf.FileName); var task = container.AddPdfAsync(pdf, item, savePath); task.Wait(); Assert.IsTrue(task.Result); Assert.IsTrue(File.Exists(savePath)); Assert.IsTrue(container.PdfFileSet.Any(n => n.FileName == pdf.FileName)); } }
/// <summary> /// Main method for running the sample. /// </summary> public static SampleOutputInfo[] Run(Stream input) { // The input file is split by extracting pages from source file and inserting them in new empty PDF documents. PdfFile file = new PdfFile(input); SampleOutputInfo[] output = new SampleOutputInfo[file.PageCount]; for (int i = 0; i < file.PageCount; i++) { PdfFixedDocument document = new PdfFixedDocument(); PdfPage page = file.ExtractPage(i); document.Pages.Add(page); output[i] = new SampleOutputInfo(document, string.Format("xfinium.pdf.sample.documentsplit.{0}.pdf", i + 1)); } return output; }
private static void EnsurePdfFile(this LiteRepository repo, PdfFile value, bool updateLastSeen = true) { var pdf = repo.GetPdf(value.Md5); if (pdf == null) { value.Id = (Guid)repo.Insert <PdfFile>(value); } else { value.Id = pdf.Id; } if (updateLastSeen) { value.LastSeen = DateTime.Now; } repo.Update(value); }
/// <summary> /// Main method for running the sample. /// </summary> public static SampleOutputInfo[] Run(Stream input) { // The input file is split by extracting pages from source file and inserting them in new empty PDF documents. PdfFile file = new PdfFile(input); SampleOutputInfo[] output = new SampleOutputInfo[file.PageCount]; for (int i = 0; i < file.PageCount; i++) { PdfFixedDocument document = new PdfFixedDocument(); PdfPage page = file.ExtractPage(i); document.Pages.Add(page); output[i] = new SampleOutputInfo(document, string.Format("xfinium.pdf.sample.documentsplit.{0}.pdf", i + 1)); } return(output); }
public void FileSystemAPITest() { var filePath = Path.GetTempFileName(); var file = new PdfFile(); file.Save(filePath); var fileText = File.ReadAllText(filePath); Assert.Contains("%PDF-1.6", fileText); try { File.Delete(filePath); } catch { } }
private PdfDocument(PdfFile file) { if (file == null) throw new ArgumentNullException("file"); _file = file; int pageCount; double maxPageWidth; bool success = file.GetPDFDocInfo(out pageCount, out maxPageWidth); if (!success) throw new Win32Exception(); _pageCount = pageCount; MaximumPageWidth = maxPageWidth; }
private async Task LoadPdf(PdfFile pdf) { try { PdfiumViewer.PdfDocument doc = await Task.Run(() => { return(PdfiumViewer.PdfDocument.Load(pdf.GetFullPath())); }); pdfViewer.Document?.Dispose(); pdfViewer.Document = doc; CurrentPdf = pdf; } catch (Exception ex) { Trace.Fail(ex.ToString()); } }
public static void LoadExistedPdfDocument() { PdfFile pdfFile = new PdfFile(); PdfDocument document; //Read pdf document from stream using (FileStream fs = File.OpenRead("sample.pdf")) { document = pdfFile.Import(fs); } //Read pdf document from byte array //document = pdfFile.Import(File.ReadAllBytes("sample.pdf")); //Get page count from existing pdf file int pageCount = document.Pages.Count; Console.WriteLine(pageCount); }
public static void ReadOneBarcodeTypeFromMultiplePdfPages() { PdfFile pdf = new PdfFile("test2.pdf"); pdf.SetDPI = 72; for (int i = 0; i < pdf.FilePageCount; i++) { Image pageImage = pdf.ConvertToImage(i, 1000, 1200); Bitmap bitmap = new Bitmap(pageImage); //pageImage.Save("Page" + i + ".jpg", ImageFormat.Jpeg); string[] data = PdfBarcodeReader.Recognize(bitmap, PdfBarcodeReader.Qrcode); foreach (string result in data) { Console.WriteLine(result); } } Console.ReadKey(); }
public static void AddText2() { //This example is using document level builder(flow-like), if the text inserted is out of one page, //the builder will insert the left text on a second page automatically PdfDocument document = new PdfDocument(); //Create document level builder using (PdfDocumentBuilder builder = new PdfDocumentBuilder(document)) { //Set page size and margins builder.SectionState.PageSize = PaperTypeConverter.ToSize(PaperTypes.A4); builder.SectionState.PageMargins = new Padding(20); //Set text alignment builder.ParagraphState.HorizontalAlignment = Editing.Flow.HorizontalAlignment.Center; //Set font style builder.CharacterState.SetFont(new FontFamily("LegacySansEFOP-Book")); builder.CharacterState.FontSize = 40; builder.InsertParagraph(); builder.InsertText("Document Title"); builder.InsertLineBreak(); //Add several paragraphs to page builder.ParagraphState.HorizontalAlignment = Editing.Flow.HorizontalAlignment.Left; builder.CharacterState.FontSize = 20; for (int i = 0; i < 20; i++) { builder.InsertParagraph(); string text = ""; for (int j = 1; j < 11; j++) { text += "This is sentence " + j.ToString() + ". "; } builder.InsertText(text); builder.InsertLineBreak(); } } using (FileStream fs = File.Create("InsertText2.pdf")) { PdfFile pdfFile = new PdfFile(); pdfFile.Export(document, fs); } }
private async void share4() { string text; var s = await DisplayActionSheet("Condividi", "Annulla", null, "Visualizza PDF", "Condividi PDF", "Condividi Testo"); if (s.Contains("PDF")) { //devo creare il PDF //if (_viewModel.Group) //{ // ListGroupToString(); // text = _listStringGroup; //lista corsi raggruppati //} //else text = string.Join("\n", _viewModel.ListOrari); //lista corsi PdfFile pdf = new PdfFile() { Title = "Elenco corsi suggeriti", TitleFacolta = _viewModel.LaureaString, TitleInfo = _viewModel.AnnoSemestre, Text = text }; pdf.CreateCompleto(); await pdf.Save(); if (s.Contains("Condividi")) //Condividi PDF { DependencyService.Get <IFile>().Share(pdf._filename); } else { resetView = false; //non voglio resettare le view await pdf.Display(); //visualizza PDF } } else { //if (_viewModel.Group) // text = ListGroupToString(); //else text = _viewModel.ToString(); text += Settings.Firma; DependencyService.Get <IMethods>().Share(text); //condividi testo } }
public static void AddImageSignature2PDF() { PdfFile pdfFile = new PdfFile(); PdfDocument document = pdfFile.Import(File.ReadAllBytes("sample.pdf")); //Input your certificate and password X509Certificate2 certificate = new X509Certificate2("test.pfx", "iditect"); //First you need create a SignatureField with unique name SignatureField signatureField = new SignatureField("iDiTect Sign Field"); //Add signature object to a signature field, so we can add a visualization to it signatureField.Signature = new Signature(certificate); //Add signature info as need signatureField.Signature.Properties.Reason = "Sign by iDiTect"; signatureField.Signature.Properties.Location = "World Wide Web"; signatureField.Signature.Properties.ContactInfo = "1234567"; //Apply a visible signature widiget to represent the contents of the signature field. SignatureWidget widget = signatureField.Widgets.AddWidget(); //Set signature position and size widget.Rect = new System.Windows.Rect(new System.Windows.Point(200, 200), new System.Windows.Size(50, 50)); widget.RecalculateContent(); //Customize signature appearance, insert an image as signature displaying PageContentBuilder signatureAppearance = new PageContentBuilder(widget.Content.NormalContentSource); using (Stream imgStream = File.OpenRead("sample.jpg")) { signatureAppearance.DrawImage(imgStream); } //Add this signature to first PDF page document.Pages[0].Annotations.Add(widget); document.AcroForm.FormFields.Add(signatureField); //Digital sign feature need the stream support reading, so you have to use ReadWrite mode here using (FileStream fs = new FileStream("signed.pdf", FileMode.Create, FileAccess.ReadWrite)) { pdfFile.Export(document, fs); } }
/// <summary> /// Main method for running the sample. /// </summary> public static SampleOutputInfo[] Run(Stream input) { PdfFile file = new PdfFile(input); PdfFixedDocument document = new PdfFixedDocument(); PdfPage page = document.Pages.Add(); PdfPageOptionalContent oc1 = file.ExtractPageOptionalContentGroup(4, "1"); page.Graphics.DrawFormXObject(oc1, 0, 0, page.Width / 2, page.Height / 2); PdfPageOptionalContent oc2 = file.ExtractPageOptionalContentGroup(4, "2"); page.Graphics.DrawFormXObject(oc2, page.Width / 2, 0, page.Width / 2, page.Height / 2); PdfPageOptionalContent oc3 = file.ExtractPageOptionalContentGroup(4, "3"); page.Graphics.DrawFormXObject(oc3, 0, page.Height / 2, page.Width / 2, page.Height / 2); PdfPageOptionalContent oc4 = file.ExtractPageOptionalContentGroup(4, "4"); page.Graphics.DrawFormXObject(oc4, page.Width / 2, page.Height / 2, page.Width / 2, page.Height / 2); SampleOutputInfo[] output = new SampleOutputInfo[] { new SampleOutputInfo(document, "xfinium.pdf.sample.optionalcontentextraction.pdf") }; return output; }
public PdfFile Read(string path) { var bytes = File.ReadAllBytes(path); var reader = new PdfReaderInternal(bytes); var header = reader.ReadPdfHeader(); var objects = new List <PdfObject>(); while (reader.IsNextObject()) { objects.Add(reader.ReadObject()); } var xref = reader.ReadXref(); var trailer = reader.ReadTrailer(); var pdf = new PdfFile(header, objects, xref, trailer); CheckPdf(pdf); return(pdf); }
/* ----------------------------------------------------------------- */ /// /// GetEncryption /// /// <summary> /// Gets the Encryption object from the specified arguments. /// </summary> /// /// <param name="src">PdfReader object.</param> /// <param name="file">PDF file information.</param> /// /// <returns>Encryption object.</returns> /// /* ----------------------------------------------------------------- */ public static Encryption GetEncryption(this PdfReader src, PdfFile file) { if (file.FullAccess && string.IsNullOrEmpty(file.Password)) { return(new Encryption()); } var password = src.GetUserPassword(file); return(new Encryption { Enabled = true, Method = src.GetEncryptionMethod(), Permission = new Permission(src.Permissions), OwnerPassword = file.FullAccess ? file.Password : string.Empty, UserPassword = password, OpenWithPassword = password.HasValue(), }); }
public void ShouldCreatePDF() { string tempPath = System.IO.Path.GetTempPath() + @"\my-capture.pdf"; if (System.IO.File.Exists(tempPath)) System.IO.File.Delete(tempPath); var pdf = new PdfFile(); //Define the PDF page size and margins pdf.SetPageSize(210, 297, "mm"); pdf.SetMargins(10, 10, 10, 15, "mm"); //Add a title and informations to the PDF pdf.AddTextCenter(text: "Selenium search result", size: 20, bold: true); pdf.AddTitle("Title A"); pdf.AddText(text: "Description = Search for Eiffel tower", size: 9, color: "DarkBlue"); pdf.AddLink("http://www.test.com", "Test link"); //Add a text paragraph to the PDF file string text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet libero arcu, et molestie purus. Ut in sem lacus, sit amet rhoncus erat. In aliquet arcu at nunc porta sollicitudin. Cras ante nisl, hendrerit quis bibendum quis, egestas vitae mi. Donec ac felis at eros placerat iaculis. Nam quam sapien, scelerisque vel bibendum et, mollis sit amet augue. Nullam egestas, lectus ut laoreet vulputate, neque quam vestibulum sapien, ut vehicula nunc metus et nulla. Curabitur ac lorem augue. Nullam quis justo eu arcu volutpat ultrices ac at orci."; pdf.AddText(text: text, size: 10); pdf.AddPage(); //Take a screenschot and add it to the PDF file using (var img = new Utils().TakeScreenShot()) { pdf.AddBookmark("Bookmark"); pdf.AddTitle("Capture A"); pdf.AddImage(img, false); } pdf.SaveAs(tempPath); A.True(System.IO.File.Exists(tempPath)); A.Greater(new System.IO.FileInfo(tempPath).Length, 25000); }
protected override void Dispose(bool disposing) { if (!_disposed && disposing) { if (_file != null) { _file.Dispose(); _file = null; } _disposed = true; } }
public PdfDocument(PdfFile file) : base(PdfObjectType.Document) { _file = file; IsContainer = true; }