private void buttonStampa_Click(object sender, EventArgs e) { FindAndKillProcess("Acrobat"); FindAndKillProcess("AcroRd32"); PdfReader pdfReader = new PdfReader(@"vuota.pdf"); Rectangle size = pdfReader.GetPageSize(1); using (PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(@"barcode.pdf", FileMode.Create))) { foreach (var p in pagine.Select((obj, i) => new { Index = i, Lista = obj })) { var indice = p.Index; var pagina = p.Lista; if (indice > 0) { pdfStamper.InsertPage(indice + 1, size); } PdfContentByte cb = pdfStamper.GetUnderContent(indice + 1); foreach (var cf in pagina) { cb.AddImage(creaCodiceBarre(cb, cf, pagina.IndexOf(cf))); } } pdfStamper.Close(); } Process.Start(@"barcode.pdf"); }
/// <summary> /// /// </summary> /// <param name="pdfPath"></param> /// <param name="imagePath"></param> /// <param name="info"></param> /// <param name="x"></param> /// <param name="y"></param> private static void AddImageToPdf(string pdfPath, string imagePath, float x, float y) { if (string.IsNullOrWhiteSpace(pdfPath) || string.IsNullOrWhiteSpace(imagePath)) { throw new ArgumentException(); } if (!File.Exists(pdfPath) || !File.Exists(imagePath)) { throw new FileNotFoundException(); } var srcPath2 = "result.pdf"; using (Stream inputPdfStream = new FileStream(pdfPath, FileMode.Open, FileAccess.ReadWrite)) using (Stream inputImageStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read)) using (Stream outputPdfStream = new FileStream(srcPath2, FileMode.Create, FileAccess.Write, FileShare.None)) { var reader = new PdfReader(inputPdfStream); var stamper = new PdfStamper(reader, outputPdfStream); stamper.InsertPage(reader.NumberOfPages, PageSize.A4); var pdfConcat = new PdfConcatenate(outputPdfStream); var pdfContentByte = stamper.GetOverContent(reader.NumberOfPages); Image image = Image.GetInstance(inputImageStream); image.SetAbsolutePosition(x, y); image.ScaleToFit(new Rectangle(100, 100)); pdfContentByte.AddImage(image); Paragraph elements = new Paragraph(); //pdfContentByte.AddOutline() stamper.Close(); } //允许抛出异常 File.Copy(srcPath2, pdfPath, true); }
// --------------------------------------------------------------------------- /** * Manipulates a PDF file src * @param src the original PDF * @param stationery the resulting PDF */ public byte[] ManipulatePdf(byte[] src, byte[] stationery) { ColumnText ct = new ColumnText(null); string SQL = @"SELECT country, id FROM film_country ORDER BY country "; using (var c = AdoDB.Provider.CreateConnection()) { c.ConnectionString = AdoDB.CS; using (DbCommand cmd = c.CreateCommand()) { cmd.CommandText = SQL; c.Open(); using (var r = cmd.ExecuteReader()) { while (r.Read()) { ct.AddElement(new Paragraph( 24, new Chunk(r["country"].ToString()) )); } } } } // Create a reader for the original document and for the stationery PdfReader reader = new PdfReader(src); PdfReader rStationery = new PdfReader(stationery); using (MemoryStream ms = new MemoryStream()) { // Create a stamper using (PdfStamper stamper = new PdfStamper(reader, ms)) { // Create an imported page for the stationery PdfImportedPage page = stamper.GetImportedPage(rStationery, 1); int i = 0; // Add the content of the ColumnText object while (true) { // Add a new page stamper.InsertPage(++i, reader.GetPageSize(1)); // Add the stationary to the new page stamper.GetUnderContent(i).AddTemplate(page, 0, 0); // Add as much content of the column as possible ct.Canvas = stamper.GetOverContent(i); ct.SetSimpleColumn(36, 36, 559, 770); if (!ColumnText.HasMoreText(ct.Go())) { break; } } } return(ms.ToArray()); } }
public int TriggerNewPage(PdfStamper stamper, Rectangle pagesize, ColumnText column, Rectangle rect, int pagecount) { stamper.InsertPage(pagecount, pagesize); PdfContentByte canvas = stamper.GetOverContent(pagecount); column.Canvas = canvas; column.SetSimpleColumn(rect); return(column.Go()); }
//-------------------------------------------------------------------------------------------------- void InsertPage(PdfStamper stamper, int iPosition, Rectangle rect) { stamper.InsertPage(iPosition, rect); PdfContentByte canvas = stamper.GetOverContent(iPosition); canvas.BeginText(); canvas.SetFontAndSize(GetDefaultFont(), 12); canvas.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "<Страница отсутствует>", (rect.Left + rect.Right) / 2, (rect.Bottom + rect.Top) / 2, 0); canvas.EndText(); }
public static bool InsertPages(string sourcePdf, string insertPdf, int pagenumber) { //variables //String first_source = "D:/myprogram/pdf/htmlpdf.pdf"; //String second_source = "d:/pdfcontentadded.pdf"; string pathout = Guid.NewGuid().ToString() + ".pdf"; //@"C:\doMain.Utils\inDigitalization\pdfout.pdf"; //create a document object //var doc = new Document(PageSize.A4); //create PdfReader objects to read pages from the source files PdfReader reader = new PdfReader(insertPdf); PdfReader reader1 = new PdfReader(sourcePdf); //create PdfStamper object to write to the pages read from readers PdfStamper stamper = new PdfStamper(reader1, new FileStream(pathout, FileMode.Create)); //get one page from htmlpdf.pdf PdfImportedPage page = stamper.GetImportedPage(reader, 1); //the page gotten from htmlpdf.pdf will be inserted at the second page in the first source doc stamper.InsertPage(pagenumber, reader1.GetPageSize(1)); //insert the page PdfContentByte pb = stamper.GetUnderContent(pagenumber); pb.AddTemplate(page, 0, 0); //close the stamper stamper.Close(); reader.Close(); reader1.Close(); reader.Dispose(); reader1.Dispose(); FileUtils.Delete(sourcePdf, true); FileUtils.CopyBlocking(pathout, sourcePdf); FileUtils.Delete(pathout); return(true); }
private bool combinedImposedCoverAndBrief(string srcBrief, string srcCover, string dest) { try { using (var stream = new System.IO.FileStream(dest, System.IO.FileMode.Create)) { Document pdfdoc = new Document(new iTextSharp.text.Rectangle(1031.76f, 728.64f)); PdfCopy pdfcopy = new PdfCopy(pdfdoc, stream); pdfdoc.Open(); string[] files = { srcCover, srcBrief }; // merge pdfs in folder string f; for (int i = 0; i < files.Length; i++) { f = files[i]; // read file PdfReader reader = new PdfReader(f); // add blank page if needed if (i == 0 && reader.NumberOfPages == 1) // if NumPages == 2, then brief has inside cover { PdfStamper stamper = new PdfStamper(reader, stream); //stamper.Writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_4); stamper.InsertPage(reader.NumberOfPages + 1, reader.GetPageSizeWithRotation(1)); } pdfcopy.AddDocument(reader); reader.Close(); } pdfcopy.Close(); pdfdoc.Close(); } return(true); } catch (Exception excpt) { System.Diagnostics.Debug.WriteLine(excpt); return(false); } }
public static void SignHashed(MemoryStream Source, string Target, SysX509.X509Certificate2 Certificate, string Reason, string Location, bool AddVisibleSign, Image img, int nroHojaFirma, string path, float h, string att_1, string att_2, string att_3, string url_terminos) { try { X509CertificateParser objCP = new X509CertificateParser(); X509Certificate[] objChain = new X509Certificate[] { objCP.ReadCertificate(Certificate.RawData) }; IExternalSignature externalSignature = new X509Certificate2Signature(Certificate, "SHA-1"); PdfReader objReader = new PdfReader(Source); //string[] msg = Certificate.SubjectName.Name.Split(','); //Document document = new Document(PageSize.A4, 50, 50, 150, 100); //PdfWriter pdfwritter = PdfWriter.GetInstance(document, new FileStream("C:\\Users\\Public\\terminos_condiciones.pdf", FileMode.OpenOrCreate)); using (PdfReader readerTerm = new PdfReader(url_terminos)) using (MemoryStream workStream = new MemoryStream()) { PdfStamper objStamper = PdfStamper.CreateSignature(objReader, new FileStream(Target, FileMode.OpenOrCreate, FileAccess.Write), '\0'); int nroPages = objReader.NumberOfPages + 1; Rectangle rectangle = readerTerm.GetPageSize(1); objStamper.InsertPage(nroPages, rectangle); PdfImportedPage bg = objStamper.GetImportedPage(readerTerm, 1); objStamper.GetUnderContent(nroPages).AddTemplate(bg, 0, 0); PdfSignatureAppearance objSA = objStamper.SignatureAppearance; img.ScaleAbsolute(120f, 60f); img.SetAbsolutePosition(0, 28); BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false); BaseFont bfBold = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, false); if (true) { objSA.SetVisibleSignature(new Rectangle(50, h - 120, 200, h), nroHojaFirma, "Firma Digital emitida por el sistema BV Digital"); } PdfTemplate n2Layer = objSA.GetLayer(2); n2Layer.BeginText(); n2Layer.SetFontAndSize(bfBold, 7); n2Layer.ShowTextAligned(Element.ALIGN_LEFT, "Inspectorate Services Perú S.A.C", 0, 100, 0); n2Layer.ShowTextAligned(Element.ALIGN_LEFT, "A Bureau Veritas Group Company", 0, 90, 0); n2Layer.EndText(); n2Layer.AddImage(img); n2Layer.BeginText(); n2Layer.SetFontAndSize(bf, 7); n2Layer.ShowTextAligned(Element.ALIGN_LEFT, "Firmado Digitalmente por", 0, 40, 0); //string user = msg[2].Substring(msg[2].IndexOf('=') + 1); //user += " " + msg[3].Substring(msg[3].IndexOf('=') + 1); n2Layer.ShowTextAligned(Element.ALIGN_LEFT, att_3, 0, 30, 0); n2Layer.ShowTextAligned(Element.ALIGN_LEFT, "Fecha: " + objSA.SignDate.ToString(), 0, 20, 0); n2Layer.ShowTextAligned(Element.ALIGN_LEFT, att_1, 0, 10, 0); n2Layer.ShowTextAligned(Element.ALIGN_LEFT, att_2, 0, 0, 0); n2Layer.EndText(); objSA.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION; MakeSignature.SignDetached(objSA, externalSignature, objChain, null, null, null, 0, CryptoStandard.CMS); objStamper.SetFullCompression(); } } catch (Exception e) { Utility.log_err.save(null, e); } }
private void btnPdf_Click(object sender, EventArgs e) { if (txtLicPdfCode.Text == "" || txtLicPdfCode.Text == "Enter Pdf Verfication Code") { txtLicPdfCode.Focus(); errorProvider1.SetError(txtLicPdfCode, "Enter Pdf Verfication Code"); return; } else { errorProvider1.Clear(); } var vehicelDetails = GetVehicelDetialsByLicPdfCode(txtLicPdfCode.Text); if (vehicelDetails != null && vehicelDetails.VehicelId != 0) { RequestToke token = Service_db.GetLatestToken(); if (ObjToken != null) { parternToken = token.Token; } pictureBox2.Visible = true; pictureBox2.WaitOnLoad = true; String WebUrlPath = WebConfigurationManager.AppSettings["WebUrlPath"]; string filePath = WebUrlPath + "/" + "Documents/License/" + vehicelDetails.VehicelId + ".pdf"; string optionalFilePath = WebUrlPath + "/" + "Documents/License/" + vehicelDetails.RegistrationNo + ".pdf"; //urlPath //var pdfPath = SavePdfFromUrl(filePath, optionalFilePath); //// var pdfPath = @"F:\sample.pdf"; //PdfDocument doc = new PdfDocument(); //doc.LoadFromFile(pdfPath); //doc.Pages.Insert(0); //doc.Pages.Add(); //doc.Pages.RemoveAt(0);//Since First page have always Red Text if use Free Version. //doc.SaveToFile(pdfPath); string installedPath = @"C:\Users\Public\"; string fileName = "Certificate" + ".pdf"; var destinationFileName = System.IO.Path.Combine(installedPath, System.IO.Path.GetFileName(fileName)); PdfReader reader = new PdfReader(filePath); PdfStamper stamper = new PdfStamper(reader, new FileStream(destinationFileName, FileMode.Create)); int total = reader.NumberOfPages; for (int pageNumber = total; pageNumber > 0; pageNumber--) { stamper.InsertPage(pageNumber, PageSize.A4); } stamper.Close(); reader.Close(); MyMessageBox.ShowBox("Please Print Licence Disk. ", "Print License Disk"); printPDFWithAcrobat(destinationFileName); pictureBox2.Visible = false; riskDetail = new RiskDetailModel { CombinedID = vehicelDetails.CombinedID, LicenseId = vehicelDetails.LicenseId, RegistrationNo = vehicelDetails.RegistrationNo }; this.Close(); WebCertificateSerial obj = new WebCertificateSerial(riskDetail, parternToken); obj.Show(); } else { pictureBox2.Visible = false; MyMessageBox.ShowBox("Certificate is not found for this code", "Message"); } pictureBox2.Visible = false; }
public string CreatePDF(int poid) { var po = OrderRepository.Single(poid); if (po == null) { throw new ItemNotFoundException <Ordering.PurchaseOrder>(x => x.POID, poid); } var basePath = ConfigurationManager.AppSettings["PdfBasePath"]; if (string.IsNullOrEmpty(basePath)) { throw new InvalidOperationException("Missing required appSetting: PdfBasePath"); } if (!Directory.Exists(basePath)) { throw new InvalidOperationException($"Directory not found: {basePath}"); } string tempPath = Path.Combine(basePath, "temp"); if (!Directory.Exists(tempPath)) { Directory.CreateDirectory(tempPath); } string imagePath = Path.Combine(basePath, "images"); if (!Directory.Exists(imagePath)) { Directory.CreateDirectory(imagePath); } string template = Path.Combine(basePath, "IOFTemplate.pdf"); if (!File.Exists(template)) { throw new InvalidOperationException($"Missing template file: {template}"); } string templatePage2 = Path.Combine(basePath, "IOFTemplatePage2.pdf"); if (!File.Exists(templatePage2)) { throw new InvalidOperationException($"Missing template page 2 file: {templatePage2}"); } var c = ClientRepository.Single(po.ClientID); string pdfName = $"IOF_{po.POID}_{c.LName}{c.FName}_{DateTime.Now:yyMmddHHmmss}.pdf"; string pdfPath = Path.Combine(tempPath, pdfName); if (File.Exists(pdfPath)) { File.Delete(pdfPath); } using (var fs = new FileStream(pdfPath, FileMode.Create, FileAccess.Write)) { PdfReader pr = new PdfReader(template); PdfStamper ps = new PdfStamper(pr, fs); AcroFields af = ps.AcroFields; var info = pr.Info; info["Title"] = $"IOF #{po.POID} : {po.VendorName} : {c.FName} {c.LName}"; ps.MoreInfo = info; using (var ms = new MemoryStream()) { var xmp = new XmpWriter(ms, info); ps.XmpMetadata = ms.ToArray(); xmp.Close(); } af.SetField("poID", $"IOF # {po.POID}"); af.SetField("RequestedBy", c.DisplayName); af.SetField("Email", c.Email); af.SetField("Phone", c.Phone); var approver = ClientRepository.GetApprover(po); if (po.IsApproved()) { string imageFile = Path.Combine(imagePath, $"{approver.LName}.tif"); if (File.Exists(imageFile)) { var sig = Image.GetInstance(imageFile); ps.GetOverContent(1).AddImage(sig, 50, 0, 0, 24, 231, 539); } af.SetField("ApprovedBy", approver.DisplayName); } // fill in shipping info af.SetField("Date", po.CreatedDate.ToShortDateString()); af.SetField("DateNeeded", po.NeededDate.ToShortDateString()); af.SetField("Advisor", approver.DisplayName); af.SetField("Shipping", po.ShippingMethodName); var acct = AccountRepository.Single(po.ClientID, po.AccountID); if (acct == null) { af.SetField("Account", string.Empty); } else { af.SetField("Account", acct.ShortCode); } if (po.Oversized) { af.SetField("chkOverSized", "Yes"); } af.SetField("PurchaseTotal", po.TotalPrice.ToString("#,##0.00")); // fill in vendor info var vendor = VendorRepository.Single(po.VendorID); af.SetField("Vendor", vendor.VendorName); af.SetField("VendAddr1", vendor.Address1); af.SetField("VendAddr2", vendor.Address2); af.SetField("VendAddr3", vendor.Address3); af.SetField("Contact", vendor.Contact); af.SetField("ContactPhone", vendor.Phone); af.SetField("ContactFax", vendor.Fax); af.SetField("VendorWWW", vendor.URL); af.SetField("ContactEmail", vendor.Email); // in the 'office use only' box af.SetField("VendorOffice", vendor.VendorName); // notes var items = GetItems(po.POID).ToList(); if (!string.IsNullOrEmpty(po.Notes)) { items.Add(new PdfItem() { Description = po.Notes, IsNotes = true }); } // items int x = 0; float y = 410F; //page 1 starting position int pageNumber = 1; float width = pr.GetPageSize(pageNumber).Width - x; //DrawLine(ps.GetOverContent(page), 280) foreach (var item in items.OrderByDescending(i => i.PODID)) { var tbl = CreateTable(item, width); if (pageNumber < 2) { if (y + tbl.TotalHeight < 280) { pageNumber = 2; y = 580; //page 2 starting position ps.InsertPage(pageNumber, pr.GetPageSize(1)); var p2reader = new PdfReader(templatePage2); ps.ReplacePage(p2reader, 1, 2); ps.Writer.FreeReader(p2reader); p2reader.Close(); //DrawLine(ps.GetOverContent(page), 60) } } else { if (y + tbl.TotalHeight < 60) { pageNumber += 1; y = 580; //page n starting position ps.InsertPage(pageNumber, pr.GetPageSize(1)); var p2reader = new PdfReader(templatePage2); ps.ReplacePage(p2reader, 1, pageNumber); ps.Writer.FreeReader(p2reader); p2reader.Close(); //DrawLine(ps.GetOverContent(page), 60) } } var ct = new ColumnText(ps.GetOverContent(pageNumber)) { Alignment = Element.ALIGN_LEFT }; ct.SetSimpleColumn(x, y, width, y + 100); ct.AddElement(tbl); ct.Go(); y -= tbl.TotalHeight; } AddPageNumberFooter(ps, pr.NumberOfPages, width); ps.FormFlattening = true; ps.Close(); } return(pdfPath); }
private void btnScan_Click(object sender, EventArgs e) { try { pictureBox2.Visible = true; pictureBox2.WaitOnLoad = true; var pdfPath = SavePdf(_base64Data); //PdfDocument doc = new PdfDocument(); //doc.LoadFromFile(pdfPath); //doc.Pages.Insert(0); //doc.Pages.Add(); //doc.Pages.RemoveAt(0);//Since First page have always Red Text if use Free Version. //doc.SaveToFile(pdfPath); //string installedPath = @"C:\Users\Public\"; //string fileName = "Certificate" + ".pdf"; string installedPath = @"C:\Users\Public\"; string fileName = "Certificate" + ".pdf"; var destinationFileName = System.IO.Path.Combine(installedPath, System.IO.Path.GetFileName(fileName)); PdfReader reader = new PdfReader(pdfPath); PdfStamper stamper = new PdfStamper(reader, new FileStream(destinationFileName, FileMode.Create)); int total = reader.NumberOfPages; for (int pageNumber = total; pageNumber > 0; pageNumber--) { stamper.InsertPage(pageNumber, PageSize.A4); } stamper.Close(); reader.Close(); //MessageBox.Show("Please Print Licence Disk. ", "Print License Disk"); MyMessageBox.ShowBox("Please Print Licence Disk. ", "Print License Disk"); printPDFWithAcrobat(destinationFileName); CreateLicenseFile(_base64Data); CertSerialNoDetailModel model = new CertSerialNoDetailModel(); model.VehicleId = RiskDetailModel.Id; model.CertSerialNo = txtCertificateSerialNumber.Text; SaveCertSerialNum(model); // pictureBox2.WaitOnLoad = false; pictureBox2.Visible = false; txtCertificateSerialNumber.ForeColor = Color.Gray; txtCertificateSerialNumber.Focus(); } catch (Exception ex) { pictureBox2.WaitOnLoad = false; pictureBox2.Visible = false; // MessageBox.Show(ex.Message); MyMessageBox.ShowBox(ex.Message, "Modal error message"); } }
static void Main(string[] args) { byte[] modifiedByte; var pdfByte = File.ReadAllBytes(@"mono.pdf"); var reader = new PdfReader(pdfByte); int numPages = reader.NumberOfPages; using (MemoryStream outputStream = new MemoryStream()) { var stamper = new PdfStamper(reader, outputStream); var pageSize = reader.GetPageSize(1); Console.WriteLine("Width :" + pageSize.Width + "-- Height :" + pageSize.Height); if (numPages % 2 == 1) { stamper.InsertPage(numPages + 1, pageSize); } var cb = stamper.GetOverContent(1); cb.BeginText(); if (_addBarcode) { var image = GetBarcodeImage(cb, "24206102894", 225, 50); image.SetAbsolutePosition(0, 0); cb.AddImage(image); } if (_addTick) { cb.SetFontAndSize(StfHelveticaTurkish, 14); cb.SetTextMatrix(173, 387 + (395 - 387) / 2); cb.ShowText("X"); } if (_addOneLineText) { //x0,y0+(ycenter-y0)/2 cb.SetFontAndSize(StfHelveticaTurkish, 12); cb.SetTextMatrix(118, 579 + (586 - 579) / 2); cb.ShowText("24206102894"); } if (_addMultiLineText) { ColumnText cvv = new ColumnText(cb); //x0,y0,x1,y1 cvv.SetSimpleColumn(new Phrase(new Chunk(_sampleSmallText)), 0, 698, 188, 842, 12, Element.ALIGN_TOP); cvv.Go(); } if (_addSpaceBetweenCharacter) { //gelen px / 2 char spacing 12 punto için 15 ise 14 için ters orantı kur cb.SetCharacterSpacing(7.5f); cb.SetFontAndSize(StfHelveticaTurkish, 12); cb.SetTextMatrix(119, 699 + (706 - 699) / 2); cb.ShowText("24206102894"); } cb.EndText(); stamper.Close(); modifiedByte = outputStream.ToArray(); } File.WriteAllBytes("test.pdf", modifiedByte); System.Diagnostics.Process.Start("test.pdf"); Console.ReadLine(); }
public Stream GetPdf() { var document = CreateDefaultDocument(); var tocDocument = CreateDefaultDocument(); var stream = new MemoryStream(); _pdfWriter = PdfWriter.GetInstance(document, stream); _pdfWriter.SetLinearPageMode(); var tocStream = new MemoryStream(); var tocWriter = PdfWriter.GetInstance(tocDocument, tocStream); tocWriter.SetLinearPageMode(); var tocEvent = new PdfEvents(tocDocument, RootDirectory); _pdfWriter.PageEvent = tocEvent; _pdfWriter.StrictImageSequence = true; document.Open(); tocDocument.Open(); AddMetaData(document); AddChapters(document); document.Close(); var fontFooter = PdfFonts.Small; var footer = new Phrase(string.Format("{0}: {1}", Documentation.Project.ProjectNumber, Documentation.Name), fontFooter); var pdfReader = new PdfReader(stream.ToArray()); stream = new MemoryStream(); var stamper = new PdfStamper(pdfReader, stream); var tableOfContents = GenerateTableOfContents(tocEvent, stamper, 0); tocDocument.Add(tableOfContents); tocDocument.Close(); var tocReader = new PdfReader(tocStream.ToArray()); var tocSize = tocReader.NumberOfPages; var toc = new ColumnText(null); var frontPage = new ColumnText(null); var hasFrontPage = Documentation.DocumentationChapters.Any(dc => dc.Chapter is GeneratedChapter && dc.Chapter.Name == "Forside"); tableOfContents = GenerateTableOfContents(tocEvent, stamper, tocSize + (hasFrontPage ? 2 : 0)); toc.AddElement(tableOfContents); var page = stamper.GetImportedPage(pdfReader, 1); int currentPage = 0; while (true) { stamper.InsertPage(++currentPage, pdfReader.GetPageSize(1)); stamper.GetUnderContent(currentPage).AddTemplate(page, 0, 0); toc.Canvas = stamper.GetOverContent(currentPage); toc.SetSimpleColumn(60, 72, PageSize.A4.Width - 60, PageSize.A4.Height - 72); if (!ColumnText.HasMoreText(toc.Go())) { break; } } if (hasFrontPage) { frontPage.AddElement(new FrontPageBuilder(Documentation, RootDirectory).GetContent()); page = stamper.GetImportedPage(pdfReader, 1); currentPage = 0; while (true) { stamper.InsertPage(++currentPage, pdfReader.GetPageSize(1)); stamper.GetUnderContent(currentPage).AddTemplate(page, 0, 0); frontPage.Canvas = stamper.GetOverContent(currentPage); frontPage.SetSimpleColumn(60, 72, PageSize.A4.Width - 60, PageSize.A4.Height - 72); if (!ColumnText.HasMoreText(frontPage.Go())) { break; } } stamper.InsertPage(++currentPage, pdfReader.GetPageSize(1)); stamper.GetUnderContent(currentPage).AddTemplate(page, 0, 0); } int totalPages = pdfReader.NumberOfPages; for (int i = 3; i <= totalPages; ++i) { var canvas = stamper.GetOverContent(i); var table = new PdfPTable(2); var rotation = stamper.Reader.GetPageRotation(i); table.SetWidths(new[] { 10, 1 }); table.TotalWidth = (rotation == 0 ? PageSize.A4.Width : PageSize.A4.Height) - 130; table.DefaultCell.Border = Rectangle.NO_BORDER; table.DefaultCell.FixedHeight = 20; table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; table.AddCell(footer); table.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT; table.AddCell(new Phrase(i.ToString(CultureInfo.InvariantCulture), fontFooter)); table.WriteSelectedRows(0, -1, 0, -1, 60, 40, canvas); } stamper.Close(); var outStream = new MemoryStream(stream.ToArray()); return(outStream); }
public void SignDetached() { if (lb.Items.Count > 0) { try { X509Certificate2 card = GetCertificate(); Org.BouncyCastle.X509.X509CertificateParser cp = new Org.BouncyCastle.X509.X509CertificateParser(); Org.BouncyCastle.X509.X509Certificate[] chain = new Org.BouncyCastle.X509.X509Certificate[] { cp.ReadCertificate(card.RawData) }; pb.Minimum = 0; pb.Maximum = lb.Items.Count; pb.Visible = true; foreach (object oFile in lb.Items) { string filePDF = oFile.ToString(); PdfReader reader = new PdfReader(filePDF); int Pagina = 1; int posX = 0, posY = 0, Altezza = 0, Larghezza = 0; //ricreo il percorso con il nome del nuovo file string file = filePDF.Substring(1 + filePDF.LastIndexOf(@"\")); string NuovoFile = filePDF.Substring(0, filePDF.LastIndexOf(@"\") + 1) + file.Substring(0, file.LastIndexOf(".")) + "_firmato.pdf"; PdfStamper stp = PdfStamper.CreateSignature(reader, new FileStream(NuovoFile, FileMode.Create), '\0', null, multiSigChkBx.Checked); PdfSignatureAppearance sap = stp.SignatureAppearance; string nPagine = reader.NumberOfPages.ToString(); sap.Reason = cbRagione.Text + nPagine; sap.Contact = tbContatto.Text; sap.Location = tbLuogo.Text; if (cbFirmaVisibile.Checked == true) //firma visibile { if (rbNuovaPagina.Checked) //firma su nuova pagina { Pagina = reader.NumberOfPages + 1; stp.InsertPage(Pagina, reader.GetPageSize(1)); iTextSharp.text.Rectangle rect = reader.GetPageSize(Pagina); int w = Convert.ToInt32(rect.Width); int h = Convert.ToInt32(rect.Height); posX = 20; posY = h - 120; Larghezza = posX + 100; Altezza = posY + 100; } else if (rbVecchiaPagina.Checked) //firma su pagina esistente { int IndiceScelto = lbPosizioneFirma.SelectedIndex; int paginaScelta = (IndiceScelto <= 3) ? 1 : reader.NumberOfPages; iTextSharp.text.Rectangle rect = reader.GetPageSize(paginaScelta); int w = Convert.ToInt32(rect.Width); int h = Convert.ToInt32(rect.Height); Pagina = paginaScelta; /* istruzioni: * 0 Prima Pagina in Alto a Sinistra * 1 Prima Pagina in Alto a Destra * 2 Prima Pagina in Basso a Sinistra * 3 Prima Pagina in Basso a Destra * 4 Ultima Pagina in Alto a Sinistra * 5 Ultima Pagina in Alto a Destra * 6 Ultima Pagina in Basso a Sinistra * 7 Ultima Pagina in Basso a Destra */ switch (IndiceScelto) { case 0: default: case 4: posX = 20; posY = h - 110; Larghezza = posX + 100; Altezza = posY + 100; break; case 1: case 5: posX = w - 110; posY = h - 110; Larghezza = posX + 100; Altezza = posY + 100; break; case 2: case 6: posX = 20; posY = 20; Larghezza = posX + 350; Altezza = posY + 70; break; case 3: case 7: posX = w - 110; posY = 20; Larghezza = posX + 100; Altezza = posY + 100; break; } } sap.SetVisibleSignature(new iTextSharp.text.Rectangle(posX, posY, Larghezza, Altezza), Pagina, null); } sap.SignDate = DateTime.Now; sap.SetCrypto(null, chain, null, null); sap.Acro6Layers = true; sap.Render = PdfSignatureAppearance.SignatureRender.Description; //.NameAndDescription; PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED); dic.Date = new PdfDate(sap.SignDate); dic.Name = PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN"); sap.Layer2Text = "Firmato Digitalmente da: " + PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN"); sap.Layer2Text += "\r\nData: " + sap.SignDate; sap.Layer2Text += "\r\nRagione: " + sap.Reason; if (sap.Reason != null) { dic.Reason = sap.Reason; } if (sap.Location != null) { dic.Location = sap.Location; } if (sap.Contact != null) { dic.Contact = sap.Contact; } sap.CryptoDictionary = dic; int contentEstimated = 56000; Dictionary <PdfName, int> exc = new Dictionary <PdfName, int>(); exc[PdfName.CONTENTS] = contentEstimated * 2 + 2; sap.PreClose(exc); Stream s = sap.GetRangeStream(); MemoryStream ss = new MemoryStream(); int read = 0; byte[] buff = new byte[8192]; while ((read = s.Read(buff, 0, 8192)) > 0) { ss.Write(buff, 0, read); } byte[] pk; if (tsaCbx.Checked) //ss.ToArray() { pk = SignMsg(ss.ToArray(), card, true, tsaCbx.Checked, TSAUrlTextBox.Text, tsaLogin.Text, tsaPwd.Text); } else { pk = SignMsg(ss.ToArray(), card, true, false, "", "", ""); } byte[] outc = new byte[contentEstimated]; PdfDictionary dic2 = new PdfDictionary(); Array.Copy(pk, 0, outc, 0, pk.Length); dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true)); sap.Close(dic2); //avanzo di 1 la progress bar pb.Increment(1); } MessageBox.Show(pb.Maximum.ToString() + " file firmati correttamente", "Operazione Completata"); pb.Visible = false; } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Messaggio dal Sistema Windows"); pb.Visible = false; } } }