public async Task ShouldConvertToPdfA2B(string level, string part, string conformance) { var path = $"/pdfa"; var fixture = $"{Program.TestProjectPath}/Fixtures/dummy.pdf"; var pdfFile = await File.ReadAllBytesAsync(fixture); var formData = new PdfFormData().WithConformanceLevel(level).Upload(pdfFile); var response = await _client.PostAsync(path, formData); var stream = await response.Content.ReadAsStreamAsync(); var pdfa = new PdfADocument(new PdfReader(stream), new PdfWriter(new MemoryStream())); var xmpMetadataBytes = pdfa.GetXmpMetadata(); var xmpMetadata = XMPMetaFactory.ParseFromBuffer(xmpMetadataBytes); var conformanceLevel = PdfAConformanceLevel.GetConformanceLevel(xmpMetadata); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(part, conformanceLevel.GetPart()); Assert.Equal(conformance, conformanceLevel.GetConformance()); }
public async Task ShouldReplaceAuthor() { var path = $"/pdfa"; var author = Guid.NewGuid().ToString("N"); var fixture = $"{Program.TestProjectPath}/Fixtures/dummy.pdf"; var pdfFile = await File.ReadAllBytesAsync(fixture); var formData = new PdfFormData() .WithConformanceLevel("PDF_A_2B") .WithAuthor(author) .Upload(pdfFile); var response = await _client.PostAsync(path, formData); var stream = await response.Content.ReadAsStreamAsync(); var pdfa = new PdfADocument(new PdfReader(stream), new PdfWriter(new MemoryStream())); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(author, pdfa.GetDocumentInfo().GetAuthor()); }
public virtual void CreatePdf(String dest) { //Initialize PDFA document with output intent PdfADocument pdf = new PdfADocument(new PdfWriter(dest), PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent ("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", new FileStream(INTENT, FileMode.Open, FileAccess.Read ))); Document document = new Document(pdf); //Fonts need to be embedded PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.WINANSI, true); Paragraph p = new Paragraph(); p.SetFont(font); p.Add(new Text("The quick brown ")); iText.Layout.Element.Image foxImage = new Image(ImageDataFactory.Create(FOX)); p.Add(foxImage); p.Add(" jumps over the lazy "); iText.Layout.Element.Image dogImage = new iText.Layout.Element.Image(ImageDataFactory.Create(DOG)); p.Add(dogImage); document.Add(p); document.Close(); }
private void ManipulatePdf(String dest) { PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.IDENTITY_H); Stream fileStream = new FileStream("../../../resources/data/sRGB_CS_profile.icm", FileMode.Open, FileAccess.Read); PdfADocument pdfDoc = new PdfADocument(new PdfWriter(dest), PdfAConformanceLevel.PDF_A_1A, new PdfOutputIntent("Custom", "", null, "sRGB IEC61966-2.1", fileStream)); pdfDoc.GetCatalog().SetLang(new PdfString("nl-nl")); pdfDoc.SetTagged(); Document doc = new Document(pdfDoc); doc.SetMargins(MARGIN_OF_ONE_CM, MARGIN_OF_ONE_CM, MARGIN_OF_ONE_CM, MARGIN_OF_ONE_CM); PdfDocumentInfo info = pdfDoc.GetDocumentInfo(); info .SetTitle("title") .SetAuthor("Author") .SetSubject("Subject") .SetCreator("Creator") .SetKeywords("Metadata, iText, PDF") .SetCreator("My program using iText") .AddCreationDate(); Paragraph element = new Paragraph("Hello World").SetFont(font).SetFontSize(10); doc.Add(element); Image logoImage = new Image(ImageDataFactory.Create(LOGO)); logoImage.GetAccessibilityProperties().SetAlternateDescription("Logo"); doc.Add(logoImage); doc.Close(); }
private static void DoConvertToPdfA(Stream pdfInput, Metadata metadata, Stream pdfAOutput) { var conformance = PdfAConformanceLevel.PDF_A_2B; using (var originalPdf = new PdfDocument(new PdfReader(pdfInput))) { var IccProfile = Convert.FromBase64String("AAAMSExpbm8CEAAAbW50clJHQiBYWVogB84AAgAJAAYAMQAAYWNzcE1TRlQAAAAASUVDIHNSR0IAAAAAAAAAAAAAAAAAAPbWAAEAAAAA0y1IUCAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAARY3BydAAAAVAAAAAzZGVzYwAAAYQAAABsd3RwdAAAAfAAAAAUYmtwdAAAAgQAAAAUclhZWg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wn8jf4R/5YBHgKiBCoFrgc2CMIKSgvSDV4O6hB2EgITjhUeFq4YOhnKG14c7h5+IBIhpiM6JM4mZif6KZIrKizCLlov8jGOMyo0xjZiN/45mjs6PNo+ekAaQbpDWkT+RqJIRknqS45NNk7aUIJSKlPSVX5XJljSWn5cKl3WX4JhMmLiZJJmQmfyaaJrVm0Kbr5wcnImc951kndKeQJ6unx2fi5/6oGmg2KFHobaiJqKWowajdqPmpFakx6U4pammGqaLpv2nbqfgqFKoxKk3qamqHKqPqwKrdavprFys0K1ErbiuLa6hrxavi7AAsHWw6rFgsdayS7LCszizrrQltJy1E7WKtgG2ebbwt2i34LhZuNG5SrnCuju6tbsuu6e8IbybvRW9j74KvoS+/796v/XAcMDswWfB48JfwtvDWMPUxFHEzsVLxcjGRsbDx0HHv8g9yLzJOsm5yjjKt8s2y7bMNcy1zTXNtc42zrbPN8+40DnQutE80b7SP9LB00TTxtRJ1MvVTtXR1lXW2Ndc1+DYZNjo2WzZ8dp22vvbgNwF3IrdEN2W3hzeot8p36/gNuC94UThzOJT4tvjY+Pr5HPk/OWE5g3mlucf56noMui86Ubp0Opb6uXrcOv77IbtEe2c7ijutO9A78zwWPDl8XLx//KM8xnzp/Q09ML1UPXe9m32+/eK+Bn4qPk4+cf6V/rn+3f8B/yY/Sn9uv5L/tz/bf//"); var pdfADocument = new PdfADocument(new PdfWriter(pdfAOutput), conformance, new PdfOutputIntent("Custom", "", "https://www.color.org", "sRGB IEC61966-2.1", new MemoryStream(IccProfile))); using (var newDocument = new Document(pdfADocument)) { newDocument.SetMargins(0, 0, 0, 0); // copy pages originalPdf.CopyPagesTo(1, originalPdf.GetNumberOfPages(), newDocument.GetPdfDocument()); // add metadata AddMetadata(originalPdf, newDocument, metadata); // save on close } } }
private void ManipulatePdf(String dest) { PdfFont font = PdfFontFactory.CreateFont(FONT, PdfEncodings.IDENTITY_H); FileStream fileStream = new FileStream("../../../resources/data/sRGB_CS_profile.icm", FileMode.Open, FileAccess.Read); PdfADocument pdfDoc = new PdfADocument(new PdfWriter(dest), PdfAConformanceLevel.PDF_A_2A, new PdfOutputIntent("Custom", "", null, "sRGB IEC61966-2.1", fileStream)); Document document = new Document(pdfDoc); // Specifies that document should contain tag structure pdfDoc.SetTagged(); pdfDoc.GetCatalog().SetLang(new PdfString("en-us")); Paragraph p = new Paragraph("Hello World!").SetFont(font).SetFontSize(10); document.Add(p); document.Close(); }
public async Task ShouldReplaceCreationDate() { var path = $"/pdfa"; var creationDate = new DateTime(1980, 10, 10); var fixture = $"{Program.TestProjectPath}/Fixtures/dummy.pdf"; var pdfFile = await File.ReadAllBytesAsync(fixture); var formData = new PdfFormData() .WithConformanceLevel("PDF_A_2B") .WithCreationDate(creationDate) .Upload(pdfFile); var response = await _client.PostAsync(path, formData); var stream = await response.Content.ReadAsStreamAsync(); var pdfa = new PdfADocument(new PdfReader(stream), new PdfWriter(new MemoryStream())); var creationDateProperty = PdfName.CreationDate.GetValue(); var pdfaCreationDate = pdfa.GetDocumentInfo().GetMoreInfo(creationDateProperty); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(creationDate, Convert.ToDateTime(pdfaCreationDate)); }
public async Task ShouldAddCustomProperties() { var path = $"/pdfa"; var prop1 = Guid.NewGuid().ToString("N"); var prop2 = Guid.NewGuid().ToString("N"); var fixture = $"{Program.TestProjectPath}/Fixtures/dummy.pdf"; var pdfFile = await File.ReadAllBytesAsync(fixture); var formData = new PdfFormData().WithConformanceLevel("PDF_A_2B") .AddCustomProperty(nameof(prop1), prop1) .AddCustomProperty(nameof(prop2), prop2) .Upload(pdfFile); var response = await _client.PostAsync(path, formData); var stream = await response.Content.ReadAsStreamAsync(); var pdfa = new PdfADocument(new PdfReader(stream), new PdfWriter(new MemoryStream())); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(prop1, pdfa.GetDocumentInfo().GetMoreInfo(nameof(prop1))); Assert.Equal(prop2, pdfa.GetDocumentInfo().GetMoreInfo(nameof(prop2))); }
public byte[] MetaPDFA(byte[] file) { using (MemoryStream readingMemoryStream = new MemoryStream(file)) using (PdfReader pdfReader = new PdfReader(readingMemoryStream)) using (PdfDocument readingPdfDocument = new PdfDocument(pdfReader)) using (MemoryStream writingMemoryStream = new MemoryStream()) using (PdfWriter pdfWriter = new PdfWriter(writingMemoryStream)) using (FileStream intentFileStream = new FileStream(Intent, FileMode.Open, FileAccess.Read)) using (PdfADocument pdfaDocument = new PdfADocument(pdfWriter, PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent( "Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", intentFileStream ))) { readingPdfDocument.CopyPagesTo(1, readingPdfDocument.GetNumberOfPages(), pdfaDocument); readingPdfDocument.Close(); pdfaDocument.Close(); return(writingMemoryStream.ToArray()); } }
private void button2_Click(object sender, EventArgs e) { try { List <Orders> orders = new List <Orders>(); SqlConnection sqlCon = new SqlConnection(connectionString); SqlCommand sqlIDproduto = new SqlCommand("select max(IDprodutos) from produtos", sqlCon); sqlCon.Open(); var IDprodutos = sqlIDproduto.ExecuteScalar(); if (!(IDprodutos is DBNull)) { IDprodutos = Convert.ToInt32(sqlIDproduto.ExecuteScalar()); } for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) { orders.Add(new Orders { productId = Convert.ToInt32(IDprodutos), product = Convert.ToString(dataGridView1.Rows[i].Cells["Descricao"].Value), price = Convert.ToDouble(dataGridView1.Rows[i].Cells["Montante"].Value), qty = Convert.ToInt32(dataGridView1.Rows[i].Cells["Quantidade"].Value) }); } string filePath = @"C:\Users\EXODUS\source\repos\luisagosti\PSI1619I_LuisAgostinho_2219105\ProjetoFaturas\ProjetoFaturas\sRGB_CS_profile.icm"; string fontFile = @"C:\Users\EXODUS\source\repos\luisagosti\PSI1619I_LuisAgostinho_2219105\ProjetoFaturas\ProjetoFaturas\FreeSans.ttf"; string fileName = @"C:\Users\EXODUS\source\repos\luisagosti\PSI1619I_LuisAgostinho_2219105\ProjetoFaturas\ProjetoFaturas" + DateTime.Now.ToString("ddMMMyyyyHHmmss") + ".pdf"; PdfADocument pdf = new PdfADocument( new PdfWriter(fileName), PdfAConformanceLevel.PDF_A_1B, new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", new FileStream(filePath, FileMode.Open, FileAccess.Read))); PdfFont font = PdfFontFactory.CreateFont(fontFile, PdfEncodings.WINANSI, PdfFontFactory.EmbeddingStrategy.FORCE_EMBEDDED); Document document = new Document(pdf); document.SetFont(font); Paragraph header = new Paragraph("FATURA").SetTextAlignment(TextAlignment.CENTER).SetFontSize(20); document.Add(header); Paragraph subheader = new Paragraph("Luis Agostinho - Programa Outono").SetTextAlignment(TextAlignment.CENTER).SetFontSize(10); document.Add(subheader); LineSeparator ls = new LineSeparator(new SolidLine()); document.Add(ls); Paragraph sellerHeader = new Paragraph("Distribuido por:").SetBold().SetTextAlignment(TextAlignment.LEFT); Paragraph sellerDetail = new Paragraph("Outono - Faturação").SetTextAlignment(TextAlignment.LEFT); Paragraph sellerAddress = new Paragraph("Portugal").SetTextAlignment(TextAlignment.LEFT); Paragraph sellerContact = new Paragraph("215468795").SetTextAlignment(TextAlignment.LEFT); document.Add(sellerHeader); document.Add(sellerDetail); document.Add(sellerAddress); document.Add(sellerContact); Paragraph customerHeader = new Paragraph("Detalhes:").SetBold().SetTextAlignment(TextAlignment.RIGHT); Paragraph customerDetail = new Paragraph("Nome: " + Nome.Text).SetTextAlignment(TextAlignment.RIGHT); Paragraph customerAddress1 = new Paragraph("Morada: " + Morada.Text).SetTextAlignment(TextAlignment.RIGHT); Paragraph customerAddress2 = new Paragraph("Telefone: " + Telefone.Text).SetTextAlignment(TextAlignment.RIGHT); document.Add(customerHeader); document.Add(customerDetail); document.Add(customerAddress1); document.Add(customerAddress2); Random random = new Random(); int num = random.Next(1000); Paragraph orderNo = new Paragraph("Fatura Nº " + num).SetBold().SetTextAlignment(TextAlignment.LEFT); Paragraph invoiceTimestamp = new Paragraph("Data: " + Data.Text).SetTextAlignment(TextAlignment.LEFT); document.Add(orderNo); document.Add(invoiceTimestamp); Table table = new Table(5, true); table.SetFontSize(9); Cell headerProductId = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph("Codigo")); Cell headerProduct = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph("Produto")); Cell headerProductPrice = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph("Preço")); Cell headerProductQty = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph("Quantidade")); Cell headerTotal = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph("Total")); table.AddCell(headerProductId); table.AddCell(headerProduct); table.AddCell(headerProductPrice); table.AddCell(headerProductQty); table.AddCell(headerTotal); double grandTotalVal = 0; foreach (Orders c in orders) { Cell productid = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph(c.productId.ToString())); Cell product = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph(c.product)); Cell price = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph(c.price.ToString())); Cell qty = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph(c.qty.ToString())); var value = 0.0; for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) { value = Convert.ToDouble(dataGridView1.Rows[i].Cells["Montante"].Value); } Cell total = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph(value.ToString())); grandTotalVal += value + value * 0.23; table.AddCell(productid); table.AddCell(product); table.AddCell(price); table.AddCell(qty); table.AddCell(total); } Cell grandTotalHeader = new Cell(1, 4).SetTextAlignment(TextAlignment.RIGHT).Add(new Paragraph("Total c/IVA: ")); Cell grandTotal = new Cell(1, 1).SetTextAlignment(TextAlignment.LEFT).Add(new Paragraph(" " + grandTotalVal.ToString())); table.AddCell(grandTotalHeader); table.AddCell(grandTotal); document.Add(table); table.Flush(); table.Complete(); document.Close(); System.Diagnostics.Process.Start(fileName); } catch (Exception ex) { } }
public PdfaPages(PdfADocument pdfa) { _pdfa = pdfa; }
public PdfaMetadata(PdfADocument pdfa) { _pdfa = pdfa; }
private void ButtonStart_Click(object sender, EventArgs e) { string title = IniFile.ReadIni("metadane", "Title"); string author = IniFile.ReadIni("metadane", "Author"); string subject = IniFile.ReadIni("metadane", "Subject"); string keywords = IniFile.ReadIni("metadane", "Keywords"); string podstawaPrawna = IniFile.ReadIni("metadane_dod", "podstawa_prawna"); List <string> inputFolders = new List <string> { _inputDir }; inputFolders.AddRange(Directory.GetDirectories(_inputDir, "*", SearchOption.AllDirectories).ToList()); Dictionary <string, int> validationErrors = new Dictionary <string, int>(); Dictionary <string, int> prefiksErrors = new Dictionary <string, int>(); Dictionary <string, string> otherErrors = new Dictionary <string, string>(); foreach (string inputFolder in inputFolders) { string outputFolder = inputFolder.Replace(_inputDir, _outputDir); Directory.CreateDirectory(outputFolder); string[] inputFiles = Directory.GetFiles(inputFolder, "*.pdf", SearchOption.TopDirectoryOnly); foreach (string inputFile in inputFiles) { string outputFile = Path.Combine(outputFolder, Path.GetFileName(inputFile) ?? throw new InvalidOperationException()); PdfDocument srcPdf = new PdfDocument(new PdfReader(inputFile)); PdfOutputIntent rgbIntent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", new MemoryStream(Resources.sRGB_CS_profile)); PdfADocument outputPdf = new PdfADocument(new PdfWriter(outputFile), PdfAConformanceLevel.PDF_A_3B, rgbIntent); try { srcPdf.CopyPagesTo(1, srcPdf.GetNumberOfPages(), outputPdf); } catch (Exception exception) { srcPdf.Close(); Document document = new Document(outputPdf); document.Add(new Paragraph()); document.Close(); outputPdf.Close(); otherErrors.Add(inputFile, exception.Message); continue; } srcPdf.Close(); PdfDocumentInfo info = outputPdf.GetDocumentInfo(); info.SetCreator("GN PDF_A Creator"); info.SetTitle(title); info.SetAuthor(author); info.SetSubject(subject); info.SetKeywords(keywords); info.SetMoreInfo(@"Podstawa prawna", podstawaPrawna); string file = Path.GetFileName(outputFile); Dictionary <string, string> rodzajDokumentu = _prefix.Where(p => file.ToUpper().Contains(p.Key.ToUpper())).ToDictionary(x => x.Key, x => x.Value); if (rodzajDokumentu.Count != 1) { prefiksErrors.Add(inputFile, rodzajDokumentu.Count); info.SetMoreInfo(@"Rodzaj Dokumentu", ""); } else { info.SetMoreInfo(@"Rodzaj Dokumentu", rodzajDokumentu.Values.ElementAt(0)); } info.SetMoreInfo("software", @"The file was created by the PDF_A program using iText 7 library"); info.SetMoreInfo("license", @"This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version."); info.SetMoreInfo("copyright", @"Copyright (C) 2019 GISNET"); for (int i = 0; i <= outputPdf.GetNumberOfPdfObjects(); i++) { PdfObject pdfObject = outputPdf.GetPdfObject(i); if (pdfObject != null && pdfObject.IsStream()) { PdfStream pdfStream = (PdfStream)pdfObject; PdfObject subtype = pdfStream.Get(PdfName.Subtype); if (Equals(subtype, PdfName.Image) && pdfStream.ContainsKey(PdfName.Interpolate)) { pdfStream.Remove(PdfName.Interpolate); } } } try { outputPdf.Close(); } catch (Exception exception) { otherErrors.Add(inputFile, exception.Message); continue; } using (PDFACompliance pdfA = new PDFACompliance(false, outputFile, null, PDFACompliance.Conformance.e_Level3B, null, 10, false)) { int errCnt = pdfA.GetErrorCount(); if (errCnt > 0) { validationErrors.Add(outputFile, errCnt); } } } } using (StreamWriter errorFile = new StreamWriter(new FileStream("errors_validation.txt", FileMode.Create))) { foreach (var error in validationErrors) { errorFile.WriteLine(error.Key + ": " + error.Value); } } using (StreamWriter errorFile = new StreamWriter(new FileStream("errors_prefix.txt", FileMode.Create))) { foreach (var error in prefiksErrors) { errorFile.WriteLine(error.Key + ": " + error.Value); } } using (StreamWriter errorFile = new StreamWriter(new FileStream("errors_other.txt", FileMode.Create))) { foreach (var error in otherErrors) { errorFile.WriteLine(error.Key + ": " + error.Value); } } MessageBox.Show(@"Przetwarzanie zakończono.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); }
public Task <byte[]> GenerateTransactionHistory(TransactionHistoryPdf transactionHistoryPdf) { var output = new MemoryStream(); var iccStream = new FileStream(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _imageColorMatchingFilename), FileMode.Open, FileAccess.Read); var pdfFont = PdfFontFactory.CreateFont(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _trueTypeFontFilename), PdfEncodings.IDENTITY_H, true); try { var intent = new PdfOutputIntent("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", iccStream); var pdf = new PdfADocument(new PdfWriter(output), PdfAConformanceLevel.PDF_A_2B, intent); Document document = new Document(pdf); if (transactionHistoryPdf.Columns.Any()) { var table = new Table(6, false); table.AddCell(CreateRootCell(transactionHistoryPdf.Rows.Pid).SetFont(pdfFont)); table.AddCell(CreateRootCell(transactionHistoryPdf.Rows.TypeOfObject).SetFont(pdfFont)); table.AddCell(CreateRootCell(transactionHistoryPdf.Rows.TypeOfChanges).SetFont(pdfFont)); table.AddCell(CreateRootCell(transactionHistoryPdf.Rows.Descriptions).SetFont(pdfFont)); table.AddCell(CreateRootCell(transactionHistoryPdf.Rows.Author).SetFont(pdfFont)); table.AddCell(CreateRootCell(transactionHistoryPdf.Rows.Date).SetFont(pdfFont)); foreach (var column in transactionHistoryPdf.Columns) { table.AddCell(CreateCell(column.Pid).SetFont(pdfFont)); table.AddCell(CreateCell(column.TypeOfObject).SetFont(pdfFont)); table.AddCell(CreateCell(column.TypeOfChanges).SetFont(pdfFont)); table.AddCell(CreateCell(column.Descriptions, TextAlignment.LEFT).SetFont(pdfFont)); table.AddCell(CreateCell(column.Author, TextAlignment.LEFT).SetFont(pdfFont)); table.AddCell(CreateCell(column.Date, TextAlignment.LEFT).SetFont(pdfFont)); } document.Add(table); document.Add(new AreaBreak(AreaBreakType.NEXT_PAGE)); } document.Add(CreateNewLine().SetFont(pdfFont)); document.Add(CreateLineSeparator().SetFont(pdfFont)); document.Add(CreateTextAlignment(transactionHistoryPdf.Name).SetFont(pdfFont)); document.Add(CreateTextAlignment(transactionHistoryPdf.Originator).SetFont(pdfFont)); document.Add(CreateTextAlignment(transactionHistoryPdf.Address).SetFont(pdfFont)); document.Add(CreateTextAlignment(transactionHistoryPdf.SerialNumber).SetFont(pdfFont)); document.Add(CreateTextAlignment($"{transactionHistoryPdf.NumberOfPages}{pdf.GetNumberOfPages()}").SetFont(pdfFont)); var numberOfPages = pdf.GetNumberOfPages(); pdf.MovePage(numberOfPages, 1); for (int pageNum = 1; pageNum <= numberOfPages; pageNum++) { Rectangle pageSize = pdf.GetPage(pageNum).GetPageSize(); if (pageNum != 1) { document.ShowTextAligned(CreateTextAlignment(transactionHistoryPdf.Header, 7).SetFont(pdfFont), pageSize.GetLeft() + 35, pageSize.GetTop() - 13, pageNum, TextAlignment.LEFT, VerticalAlignment.TOP, 0); } document.ShowTextAligned(CreateText(pageNum + " / " + numberOfPages, 7).SetFont(pdfFont), pageSize.GetWidth() / 2, pageSize.GetBottom() + 15, pageNum, TextAlignment.CENTER, VerticalAlignment.BOTTOM, 0); } document.Close(); return(Task.FromResult(output.ToArray())); } finally { iccStream.Dispose(); output.Dispose(); } }