public static void Convert(string inputPath, string outputPath, string pdfAConformanceLevel) { _inputFilePath = inputPath; _pdfaConformanceLevel = (PdfAConformanceLevel)Enum.Parse(typeof(PdfAConformanceLevel), pdfAConformanceLevel); PdfReader reader = new PdfReader(_inputFilePath); Document doc = new Document(); using (MemoryStream ms = new MemoryStream()) { SetPdfAConformance(reader, doc, ms); doc.Close(); reader.Close(); using (FileStream fs = new FileStream(outputPath, FileMode.Create)) { // this is the part stumping me; I need to use a PdfStamper to write // out some values to fields on the form AFTER the pages are removed. // This works, but there doesn't seem to be a form on the copied page... var stamper = new PdfStamper(new PdfReader(ms.ToArray()), fs) { FormFlattening = true }; // write out fields here... stamper.SetFullCompression(); stamper.Close(); } } }
static long remove_embedded_fonts(FileInfo file) { try { var filename = create_dest_name(file, DEST + file.Name); using (var reader = new PdfReader(file.FullName)) { PdfObject obj; for (int i = 1; i < reader.XrefSize; ++i) { obj = reader.GetPdfObject(i); if (obj == null || !obj.IsDictionary()) { continue; } unembed_font((PdfDictionary)obj); } var fs = new FileStream(filename, FileMode.Create); var stamp = new PdfStamper(reader, fs); stamp.SetFullCompression(); stamp.Close(); return(get_file_size(filename)); } } catch (Exception e) { Console.Write(e); Console.WriteLine(); Console.WriteLine(); return(file.Length); } }
public static void Compress(this PdfInfo pdfInfo) { using (var reader = new PdfReader(pdfInfo.GetBytes())) { using (MemoryStream ms = new MemoryStream()) { using (PdfStamper stamper = new PdfStamper(reader, ms)) { stamper.Writer.CompressionLevel = 9; int total = reader.NumberOfPages + 1; for (int i = 1; i < total; i++) { reader.SetPageContent(i, reader.GetPageContent(i)); } stamper.SetFullCompression(); stamper.FormFlattening = true; stamper.AnnotationFlattening = true; stamper.FreeTextFlattening = true; reader.RemoveUnusedObjects(); } pdfInfo.UpdateBytes(ms.ToArray()); } } }
public void ProcessRequest(HttpContext context) { Context = context; Response = context.Response; Request = context.Request; try { LoadDataInternal(); } catch (ThreadAbortException) { // no-op } catch (Exception ex) { //Logger.LogError(ex); Response.Write("Error!"); Response.End(); } Response.BufferOutput = true; Response.ClearHeaders(); Response.ContentType = "application/pdf"; if (DownloadAsAttachment) { Response.AddHeader("Content-Disposition", "attachment; filename=" + (string.IsNullOrEmpty(DownloadFileName) ? context.Session.SessionID + ".pdf" : DownloadFileName)); } PdfStamper pst = null; try { PdfReader reader = new PdfReader(GetTemplateBytes()); pst = new PdfStamper(reader, Response.OutputStream); var acroFields = pst.AcroFields; pst.FormFlattening = true; pst.FreeTextFlattening = true; pst.SetFullCompression(); SetFieldsInternal(acroFields); pst.Close(); } finally { if (pst != null) { pst.Close(); } } }
public MetadataResult ApplyMetaData(string inputFileName, string outputFileName, List <DocumentData> metaDataCollection) { MetadataResult retDataCol = new MetadataResult(); PdfReader reader = null; PdfStamper stamper = null; if (metaDataCollection == null) { retDataCol.Status = "Error"; retDataCol.Message = "There has to be at least 1 metadata field that needs to be applied to the assest"; } try { reader = new PdfReader(inputFileName); //for (int i = 1; i < reader.NumberOfPages; i++) //? Do we need metadata for all the pages ? I dont know yet! //{ //getting the first page of the pdf document PdfDictionary pagedict = reader.GetPageN(1); foreach (DocumentData docData in metaDataCollection) { //Applying the meta data in the first page pagedict.Put(new PdfName(docData.Key), new PdfString(docData.Text)); } //} //updating the meta data into the output file stamper = new PdfStamper(reader, new FileStream(outputFileName, FileMode.Create, FileAccess.Write, FileShare.None)); stamper.SetFullCompression(); stamper.Close(); retDataCol.Status = "Success"; retDataCol.Message = "Metadata applied successfully.."; } catch (Exception ex) { retDataCol.Status = "Error"; retDataCol.Message = ex.ToString(); } finally { if (reader != null) { reader.Close(); } } return(retDataCol); }
public void Compress(string filePath, string outputFilePath) { PdfReader reader = new PdfReader(filePath); PdfStamper stamper = new PdfStamper(reader, new FileStream(outputFilePath, FileMode.Create), PdfWriter.VERSION_1_5); PdfWriter writer = stamper.Writer; writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_5); writer.CompressionLevel = PdfStream.BEST_COMPRESSION; reader.SetPageContent(1, reader.GetPageContent(1), PdfStream.BEST_COMPRESSION, true); reader.RemoveFields(); reader.RemoveUnusedObjects(); stamper.SetFullCompression(); stamper.Reader.RemoveUnusedObjects(); stamper.Close(); }
// --------------------------------------------------------------------------- /** * Manipulates a PDF file src with the file dest as result * @param src the original PDF */ public byte[] CompressPdf(byte[] src) { PdfReader reader = new PdfReader(src); using (MemoryStream ms = new MemoryStream()) { using (PdfStamper stamper = new PdfStamper(reader, ms, PdfWriter.VERSION_1_5)) { stamper.Writer.CompressionLevel = 9; int total = reader.NumberOfPages + 1; for (int i = 1; i < total; i++) { reader.SetPageContent(i, reader.GetPageContent(i)); } stamper.SetFullCompression(); } return ms.ToArray(); } }
static bool optimize_pdf(string src, string dest) { try { var reader = new PdfReader(src); var fs = new FileStream(dest, FileMode.Create); var stamp = new PdfStamper(reader, fs); reader.RemoveUnusedObjects(); stamp.SetFullCompression(); stamp.Close(); return(true); } catch (Exception e) { Console.Write(e); Console.WriteLine(System.Environment.NewLine); return(false); } }
static void Main(string[] args) { //MergePdf(); //Get All Files ina directory List <FileInfo> _Files = new List <FileInfo>(); foreach (var file in new DirectoryInfo(@"D:\PDF\Input").GetFiles("*.pdf", SearchOption.AllDirectories).OrderBy(x => x.Name)) { _Files.Add(file); } Parallel.ForEach(_Files, file => { PdfReader reader = new PdfReader(file.FullName); //Compress images, Specify quality as second paramter - 1 to 100 ReduceResolution(reader, 7); if (!Directory.Exists($@"D:\PDF\Output\{file.Directory.Name}")) { Directory.CreateDirectory($@"D:\PDF\Output\{file.Directory.Name}"); } using (PdfStamper stamper = new PdfStamper(reader, new FileStream($@"D:\PDF\Output\{file.Directory.Name}\{file.Name}", FileMode.Create), PdfWriter.VERSION_1_7)) { // flatten form fields and close document stamper.FormFlattening = true; stamper.SetFullCompression(); //IText document - http://itextsupport.com/apidocs/itext5/latest/com/itextpdf/text/pdf/PdfStamper.html //strength - true for 128 bit key length, false for 40 bit key length stamper.SetEncryption(true, "tk", "tk", PdfWriter.AllowPrinting); stamper.Close(); } reader.Close(); }); //MergePdf(); _Files.Clear(); _Files = null; }
public OcrResult Ocr(string pdfPath, ResultTypeEnum resultTypeEnum, string language = "tur") { var result = new OcrResult(); var doc = PDFDoc.Open(pdfPath); if (!string.IsNullOrEmpty(doc.GetText())) { return(result); } doc.Ocr(Clock.Utils.OcrMode.Tesseract, language, WriteTextMode.Word, null); if (resultTypeEnum.HasFlag(ResultTypeEnum.OcrCompressed) || resultTypeEnum.HasFlag(ResultTypeEnum.All)) { var reader = new PdfReader(doc.PDFBytes); var stamper = new PdfStamper(reader, new FileStream(Path.Combine(Path.GetTempPath(), "Clock.hocr", Path.GetFileNameWithoutExtension(pdfPath) + "ocrCompressed" + Path.GetExtension(pdfPath)), FileMode.Create), PdfWriter.VERSION_1_5); var pageNum = reader.NumberOfPages; for (var i = 1; i <= pageNum; i++) { reader.SetPageContent(i, reader.GetPageContent(i)); } stamper.SetFullCompression(); stamper.Close(); } if (resultTypeEnum.HasFlag(ResultTypeEnum.Text) || resultTypeEnum.HasFlag(ResultTypeEnum.All)) { result.Text = doc.GetText(); } if (resultTypeEnum.HasFlag(ResultTypeEnum.OcrBest) || resultTypeEnum.HasFlag(ResultTypeEnum.All)) { result.OcredBest = doc.PDFBytes; } if (resultTypeEnum.HasFlag(ResultTypeEnum.OcrCompressed) || resultTypeEnum.HasFlag(ResultTypeEnum.All)) { result.OcredCompressed = System.IO.File.ReadAllBytes(Path.Combine(Path.GetTempPath(), "Clock.hocr", Path.GetFileNameWithoutExtension(pdfPath) + "ocrCompressed" + Path.GetExtension(pdfPath))); } _fileHelper.DeleteDirectory(Path.Combine(Path.GetTempPath(), "Clock.hocr")); return(result); }
static void Main(string[] args) { byte[] compressedData; using (var memStream = new MemoryStream()) { var reader = new PdfReader(File.ReadAllBytes(@"C:\origem.pdf")); var stamper = new PdfStamper(reader, memStream, PdfWriter.VERSION_1_4); var pageNum = reader.NumberOfPages; for (var i = 1; i <= pageNum; i++) { reader.SetPageContent(i, reader.GetPageContent(i)); } stamper.SetFullCompression(); stamper.Close(); reader.Close(); compressedData = memStream.ToArray(); } File.WriteAllBytes(@"C:\inetpub\wwwroot\github\PDFCompress\src\Temp\Arquivo.pdf", compressedData); }
private void FillForm(string pdfTemplate, DeclaratiePersonala date) { PdfReader pdfReader = new PdfReader(pdfTemplate); MemoryStream outStream = new MemoryStream(); PdfStamper pdfStamper = new PdfStamper(pdfReader, outStream); AcroFields pdfFormFields = pdfStamper.AcroFields; // set form pdfFormFields // The first worksheet and W-4 form pdfFormFields.SetField("nume", date.nume); pdfFormFields.SetField("prenume", date.prenume); pdfFormFields.SetField("ziua", date.zi); pdfFormFields.SetField("luna", date.luna); pdfFormFields.SetField("anul", date.an); string adresa1; string adresa2; if (date.adresa.Length > 40) { adresa1 = date.adresa.Substring(0, 55); adresa2 = date.adresa.Substring(56); pdfFormFields.SetField("fill_8", adresa1); pdfFormFields.SetField("fill_9", adresa2); } else { pdfFormFields.SetField("fill_8", date.adresa); } pdfFormFields.SetField("locul", date.locul); if (date.motiv == "1") { pdfFormFields.SetField("Group10", "Choice1"); } if (date.motiv == "2") { pdfFormFields.SetField("Group10", "Choice2"); } if (date.motiv == "3") { pdfFormFields.SetField("Group10", "Choice3"); } if (date.motiv == "4") { pdfFormFields.SetField("Group10", "Choice4"); } if (date.motiv == "5") { pdfFormFields.SetField("Group10", "Choice5"); } if (date.motiv == "6") { pdfFormFields.SetField("Group10", "Choice6"); } if (date.motiv == "7") { pdfFormFields.SetField("Group10", "Choice7"); } if (date.motiv == "8") { pdfFormFields.SetField("Group10", "Choice8"); } if (date.motiv == "9") { pdfFormFields.SetField("Group10", "Choice9"); } if (date.motiv == "10") { pdfFormFields.SetField("Group10", "Choice10"); } pdfFormFields.SetField("data", date.zi + "/" + date.luna + "/" + date.an); pdfFormFields.SetField("semnatura", date.semnatura); pdfStamper.FormFlattening = true; // close the pdf pdfStamper.Close(); pdfStamper.SetFullCompression(); pdfStamper.Writer.CompressionLevel = 9; byte[] content = outStream.ToArray(); Response.Clear(); Response.ContentType = "application/pdf"; string pdfName = "User"; Response.AddHeader("Content-Disposition", "attachment; filename=" + pdfName + ".pdf"); Response.ContentType = "application/pdf"; Response.Buffer = true; Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.BinaryWrite(content); Response.End(); Response.Close(); }
public void SavePart(string srcFile, string dstFile, int startPage, int endPage) { PdfReader pdfReader = null; try { Cursor.Current = Cursors.WaitCursor; pdfReader = new PdfReader(srcFile); pdfReader.RemoveUnusedObjects(); if (pdfReader.NumberOfPages == 0) { throw new Exception("В документе отсутствуют страницы. Операция сохранения невозможна!"); } startPage = (startPage <= 0 || startPage > pdfReader.NumberOfPages) ? 1 : startPage; endPage = (endPage <= 0 || endPage <startPage || endPage> pdfReader.NumberOfPages) ? pdfReader.NumberOfPages : endPage; pdfReader.SelectPages(startPage.ToString() + "-" + endPage.ToString()); using (var file_stream = new FileStream(dstFile, FileMode.Create, FileAccess.Write, FileShare.None)) using (var stamper = new PdfStamper(pdfReader, file_stream)) { stamper.SetFullCompression(); for (int numberPage = startPage; numberPage <= endPage; numberPage++) { if (numberPage <= 0 || numberPage > pdfReader.NumberOfPages) { continue; } PdfDictionary page = pdfReader.GetPageN(numberPage); var resources = (PdfDictionary)PdfReader.GetPdfObject(page.Get(PdfName.RESOURCES)); var xobject = (PdfDictionary)PdfReader.GetPdfObject(resources.Get(PdfName.XOBJECT)); if (xobject != null) { foreach (PdfName pdname in xobject.Keys) { PdfObject obj = xobject.Get(pdname); if (obj.IsIndirect()) { var tg = (PdfDictionary)PdfReader.GetPdfObject(obj); //resolve indirect reference var subType = (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE)); if (PdfName.IMAGE.Equals(subType)) { int xrefIndex = ((PRIndirectReference)obj).Number; PdfObject imgPdfObj = pdfReader.GetPdfObject(xrefIndex); var imgPdfStream = (PdfStream)imgPdfObj; var imgPRStream = (PRStream)imgPdfStream; byte[] bytes = PdfReader.GetStreamBytesRaw(imgPRStream); if (bytes != null && bytes.Length > 0) { try { var pdfImage = new iTextSharp.text.pdf.parser.PdfImageObject(imgPRStream); Image img = pdfImage.GetDrawingImage(); if (img != null) { var filter = (PdfName)pdfImage.Get(PdfName.FILTER); if (filter != null) { continue; } System.Drawing.Imaging.ImageFormat format; byte[] updatedImgBytes = Controls.PdfViewControl.PDFView.ConvertImageToBytes(img, 75, out format); iTextSharp.text.Image compressedImage = iTextSharp.text.Image.GetInstance(updatedImgBytes); if (format == System.Drawing.Imaging.ImageFormat.Png) { compressedImage.Deflated = true; } PdfReader.KillIndirect(obj); stamper.Writer.AddDirectImageSimple(compressedImage, (PRIndirectReference)obj); } } catch (Exception e) { Console.WriteLine(e.ToString()); continue; } } } } } } } stamper.Close(); } } finally { if (pdfReader != null) { pdfReader.Close(); } Cursor.Current = Cursors.Default; } }
public static bool SaveTreeStructureToPDF(Dictionary <int, Dictionary <string, string> > bListFilePages, string strOutputPath) { bool bReturn = false; string strPreviousFile = "previous"; string strCurrentFile = "Current"; string OutPutfile = strOutputPath; PdfReader inputReader = null; PdfOutline outline = null; int iPageCount = 1; try { Document outputDoc = new Document(); using (MemoryStream ms = new MemoryStream()) { PdfWriter writer = PdfWriter.GetInstance(outputDoc, ms); outputDoc.Open(); outputDoc.AddDocListener(writer); for (int iIndex = 0; iIndex < bListFilePages.Count; iIndex++) { Dictionary <string, string> innerDictionary = bListFilePages.ElementAt(iIndex).Value;//.Value.ToString(); string strBookMarkName = innerDictionary.ElementAt(0).Key.ToString(); string tempPath = innerDictionary.ElementAt(0).Value.ToString(); if (tempPath.Length > 0) { string strFilePath; string strPageNumber; PdfImportedPage page = null; int iPageNumber = 1; int i = tempPath.IndexOf("#@$"); if (i != -1) { strFilePath = tempPath.Substring(0, i - 1); strPageNumber = tempPath.Substring(i + 3); strCurrentFile = strFilePath; if (strCurrentFile != strPreviousFile) { if (inputReader != null) { inputReader.Close(); inputReader = null; } inputReader = new PdfReader(strCurrentFile); } if (IsNumber(strPageNumber)) { if (strFilePath.Length > 0 && strPageNumber.Length > 0) { iPageNumber = Convert.ToInt16(strPageNumber); outputDoc.SetPageSize(inputReader.GetPageSize(iPageNumber)); PdfContentByte cb = writer.DirectContent; page = writer.GetImportedPage(inputReader, iPageNumber); ///creat bookmark here and add in template PdfOutline root = cb.RootOutline; ArrayList outlineCollection = root.Kids; outline = CheckIfOutlineISPresent(strBookMarkName, outlineCollection); if (outline == null) { outline = new PdfOutline(root, PdfAction.GotoLocalPage(iPageCount, new iTextSharp.text.pdf.PdfDestination(iTextSharp.text.pdf.PdfDestination.FITH), writer), strBookMarkName); } else { outline = new PdfOutline(outline, PdfAction.GotoLocalPage(iPageCount, new iTextSharp.text.pdf.PdfDestination(iTextSharp.text.pdf.PdfDestination.FITH), writer), strBookMarkName); } outputDoc.NewPage(); Rectangle psize = inputReader.GetPageSizeWithRotation(iPageNumber); switch (psize.Rotation) { case 0: cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); break; case 90: cb.AddTemplate(page, 0, -1f, 1f, 0, 0, psize.Height); break; case 180: cb.AddTemplate(page, -1f, 0, 0, -1f, 0, 0); break; case 270: cb.AddTemplate(page, 0, 1.0F, -1.0F, 0, psize.Width, 0); break; default: break; } iPageCount++; } } strPreviousFile = strCurrentFile; } else { if (File.Exists(tempPath)) { strCurrentFile = tempPath; } else { strCurrentFile = GetFirstFileFromTree(iIndex, bListFilePages); } if (!File.Exists(strCurrentFile)) { continue; } iPageNumber = 1; PdfContentByte cb = writer.DirectContent; ///creat bookmark here and add in template PdfOutline root = cb.RootOutline; ArrayList outlineCollection = root.Kids; outline = CheckIfOutlineISPresent(strBookMarkName, outlineCollection); if (outline == null) { outline = new PdfOutline(root, PdfAction.GotoLocalPage(iPageCount, new iTextSharp.text.pdf.PdfDestination(iTextSharp.text.pdf.PdfDestination.FITH), writer), strBookMarkName); } else { outline = new PdfOutline(outline, PdfAction.GotoLocalPage(iPageCount, new iTextSharp.text.pdf.PdfDestination(iTextSharp.text.pdf.PdfDestination.FITH), writer), strBookMarkName); } } } } if (inputReader != null) { inputReader.Close(); inputReader = null; } outputDoc.Close(); using (FileStream fs = new FileStream(OutPutfile, FileMode.Create)) { // this is the part stumping me; I need to use a PdfStamper to write // out some values to fields on the form AFTER the pages are removed. // This works, but there doesn't seem to be a form on the copied page... PdfStamper stamper = new PdfStamper(new PdfReader(ms.ToArray()), fs); // write out fields here... stamper.FormFlattening = true; stamper.SetFullCompression(); stamper.Close(); } bReturn = true; } } catch (Exception ex) { bReturn = false; } return(bReturn); }
private void btnProcess_Click(object sender, EventArgs e) { if (String.IsNullOrWhiteSpace(tbPath.Text)) { return; } dataGridView1.Rows.Clear(); Cursor = Cursors.WaitCursor; IEnumerable <string> srcFiles; if (System.IO.File.GetAttributes(tbPath.Text).HasFlag(FileAttributes.Directory)) { srcFiles = Directory.EnumerateFiles(tbPath.Text, "*.pdf", SearchOption.AllDirectories); } else { srcFiles = new string[] { tbPath.Text }; } foreach (var srcFile in srcFiles) { var dataGridRowNum = dataGridView1.Rows.Add(new object[] { srcFile, 0 }); try { SetProgress("reading..."); var reader = new UnethicalPdfReader(srcFile); var dstFile = Path.Combine(Path.GetDirectoryName(srcFile), Path.GetFileNameWithoutExtension(srcFile) + tbSuffix.Text); var outStream = new MemoryStream(); var pdfStamper = new PdfStamper(reader, outStream, reader.PdfVersion, false); pdfStamper.RotateContents = false; var processor = cbReplaceText.Checked ? new TextReplaceStreamEditor(tbReplaceMatch.Text, tbReplaceReplace.Text, rbRegEx.Checked) : new PdfContentStreamEditor(); processor.RemoveXObjects = cbRemoveXO.Checked; processor.Watermark = new Regex(tbWatermark.Text, RegexOptions.Compiled); if (cbReplaceText.Checked || cbRemoveXO.Checked) { for (int i = 1; i <= reader.NumberOfPages; i++) { processor.EditPage(pdfStamper, i); SetProgress($"page: {i} / {reader.NumberOfPages}"); } } if (cbRemoveXO.Checked && processor.WatermarkCount != reader.NumberOfPages) { MessageBox.Show($"{processor.WatermarkCount} XObjects removed, but there are {reader.NumberOfPages} pages", "Possible failure", MessageBoxButtons.OK, MessageBoxIcon.Warning); } if (cbRemoveJavascript.Checked && reader.JavaScript != null) { pdfStamper.JavaScript = ""; } pdfStamper.Writer.Info?.Clear(); pdfStamper.XmpMetadata = new byte[0]; pdfStamper.MoreInfo?.Clear(); SetProgress("writing..."); pdfStamper?.Close(); reader?.Close(); //re-compress and save the PDF var output = File.Open(dstFile, FileMode.Create); var p2 = new PdfStamper(new PdfReader(outStream.GetBuffer()), output, reader.PdfVersion); if (cbUncompressed.Checked) { p2.Writer.CompressionLevel = PdfStream.NO_COMPRESSION; } else { p2.Writer.CompressionLevel = PdfStream.BEST_COMPRESSION; p2.SetFullCompression(); } p2.Close(); SetProgress("done"); dataGridView1.Rows[dataGridRowNum].ErrorText = "";; } catch (Exception ex) { dataGridView1.Rows[dataGridRowNum].ErrorText = ex.Message; } Application.DoEvents(); } Cursor = Cursors.Arrow; }
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 btnProcess_Click(object sender, EventArgs e) { if (String.IsNullOrWhiteSpace(tbPath.Text)) { return; } dataGridView1.Rows.Clear(); Cursor = Cursors.WaitCursor; IEnumerable <string> srcFiles; if (System.IO.File.GetAttributes(tbPath.Text).HasFlag(FileAttributes.Directory)) { srcFiles = Directory.EnumerateFiles(tbPath.Text, "*.pdf", SearchOption.AllDirectories); } else { srcFiles = new string[] { tbPath.Text }; } foreach (var srcFile in srcFiles) { var dataGridRowNum = dataGridView1.Rows.Add(new object[] { srcFile, 0 }); PdfReader reader = null; PdfStamper pdfStamper = null; try { reader = new PdfReader(srcFile); var dstFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(srcFile), System.IO.Path.GetFileNameWithoutExtension(srcFile) + "_clean.pdf"); var output = File.Open(dstFile, FileMode.Create); pdfStamper = new PdfStamper(reader, output, reader.PdfVersion, false); pdfStamper.RotateContents = false; var replaceTextProcessor = new TextReplaceStreamEditor(tbReplaceMatch.Text, tbReplaceReplace.Text); if (cbReplaceText.Checked) { for (int i = 1; i <= reader.NumberOfPages; i++) { replaceTextProcessor.EditPage(pdfStamper, i); } } var redactTextProcessor = new TextRedactStreamEditor(tbRedactMatch.Text); if (cbRedactText.Checked) { for (int i = 1; i <= reader.NumberOfPages; i++) { redactTextProcessor.EditPage(pdfStamper, i); } pdfStamper.Writer.SetEncryption(null, Encoding.UTF8.GetBytes("ownerPassword"), PdfWriter.AllowDegradedPrinting | PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_256); } if (cbRemoveJavascript.Checked && reader.JavaScript != null) { pdfStamper.JavaScript = ""; } pdfStamper.Writer.CompressionLevel = PdfStream.BEST_COMPRESSION; pdfStamper.SetFullCompression(); pdfStamper.Writer.Info?.Clear(); pdfStamper.XmpMetadata = new byte[0]; pdfStamper.MoreInfo?.Clear(); dataGridView1.Rows[dataGridRowNum].ErrorText = "";; } catch (Exception ex) { dataGridView1.Rows[dataGridRowNum].ErrorText = ex.Message; } finally { pdfStamper?.Close(); reader?.Close(); } } Cursor = Cursors.Arrow; }