// --------------------------------------------------------------------------- /** * Show keys and values passed to the query string with GET */ protected void DoGet(byte[] pdf, Stream stream) { // We get a resource from our web app PdfReader reader = new PdfReader(pdf); // Now we create the PDF using (PdfStamper stamper = new PdfStamper(reader, stream)) { // We add a submit button to the existing form PushbuttonField button = new PushbuttonField( stamper.Writer, new Rectangle(90, 660, 140, 690), "submit" ); button.Text = "POST"; button.BackgroundColor = new GrayColor(0.7f); button.Visibility = PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT; PdfFormField submit = button.Field; submit.Action = PdfAction.CreateSubmitForm( WebContext.Request.RawUrl, null, 0 ); stamper.AddAnnotation(submit, 1); // We add an extra field that can be used to upload a file TextField file = new TextField( stamper.Writer, new Rectangle(160, 660, 470, 690), "image" ); file.Options = TextField.FILE_SELECTION; file.BackgroundColor = new GrayColor(0.9f); PdfFormField upload = file.GetTextField(); upload.SetAdditionalActions(PdfName.U, PdfAction.JavaScript( "this.getField('image').browseForFileToSubmit();" + "this.getField('submit').setFocus();", stamper.Writer ) ); stamper.AddAnnotation(upload, 1); } }
public void setPDF() { string imgpath = Server.MapPath("~/Sign/21.jpg"); string pdfpath = Server.MapPath("~/TemplateStore/Forms/Nf packet.pdf"); string pdfpathourput = Server.MapPath("~/TemplateStore/Forms/Demo.pdf"); using (Stream inputPdfStream = new FileStream(pdfpath, FileMode.Open, FileAccess.Read, FileShare.Read)) using (Stream inputImageStream = new FileStream(imgpath, FileMode.Open, FileAccess.Read, FileShare.Read)) using (Stream outputPdfStream = new FileStream(pdfpathourput, FileMode.Create, FileAccess.Write, FileShare.None)) { var reader = new iTextSharp.text.pdf.PdfReader(inputPdfStream); int val = reader.NumberOfPages; var stamper = new iTextSharp.text.pdf.PdfStamper(reader, outputPdfStream); var pdfContentByte = stamper.GetOverContent(1); iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream); image.SetAbsolutePosition(759f, 459f); pdfContentByte.AddImage(image); stamper.Close(); } }
public static void CropPdf() { var xll = 200; var yll = 170; var w = 800; var h = 800; var reader = new iTextSharp.text.pdf.PdfReader(@"C:\Projects\31g\trunk\temp\pdf\20140208110036_20.pdf"); var n = reader.NumberOfPages; iTextSharp.text.pdf.PdfDictionary pageDict; var pfgRect = new iTextSharp.text.pdf.PdfRectangle(xll, yll, w, h); for (var i = 1; i <= n; i++) { pageDict = reader.GetPageN(i); pageDict.Put(iTextSharp.text.pdf.PdfName.CROPBOX, pfgRect); } var stamper = new iTextSharp.text.pdf.PdfStamper(reader, new System.IO.FileStream(string.Format(@"C:\Projects\31g\trunk\Notes\misc\Maps\Europe_565BCE.pdf", xll, yll, w, h), FileMode.Create)); stamper.Close(); reader.Close(); }
/// <summary> /// uses itextsharp 4.1.6 to convert any pdf to 1.4 compatible pdf, called instead of PdfReader.open /// </summary> static public PdfDocument Open(MemoryStream sourceStream, string password = null) { PdfDocument outDoc; sourceStream.Position = 0; var mode = PdfDocumentOpenMode.Modify; try { outDoc = PdfReader.Open(sourceStream, mode); } catch (PdfReaderException) { sourceStream.Position = 0; var outputStream = new MemoryStream(); var reader = password == null ? new TextSharp.PdfReader(sourceStream) : new TextSharp.PdfReader(sourceStream, Encoding.UTF8.GetBytes(password)); var pdfStamper = new iTextSharp.text.pdf.PdfStamper(reader, outputStream) { FormFlattening = true }; pdfStamper.Writer.SetPdfVersion(iTextSharp.text.pdf.PdfWriter.PDF_VERSION_1_4); pdfStamper.Writer.CloseStream = false; pdfStamper.Close(); outDoc = PdfReader.Open(outputStream, mode); } return(outDoc); }
public virtual void TestFlattening() { const string INPUT_FOLDER = RESOURCES_FOLDER + "input/"; const string CMP_FOLDER = RESOURCES_FOLDER + "cmp/"; if (File.Exists(INPUT_FOLDER)) Assert.Fail("Input folder can't be found (" + INPUT_FOLDER + ")"); Directory.CreateDirectory(OUTPUT_FOLDER); String[] files = Directory.GetFiles(INPUT_FOLDER, "*.pdf"); foreach (String file in files) { // flatten fields PdfReader reader = new PdfReader(file); PdfStamper stamper = new PdfStamper(reader, new FileStream(OUTPUT_FOLDER + Path.GetFileName(file), FileMode.Create)); stamper.FormFlattening = true; stamper.Close(); // compare CompareTool compareTool = new CompareTool(); String errorMessage = compareTool.Compare(OUTPUT_FOLDER + Path.GetFileName(file), CMP_FOLDER + Path.GetFileName(file), OUTPUT_FOLDER, "diff"); if (errorMessage != null) { Assert.Fail(errorMessage); } } }
public SignAndDatePDF(ByteBuffer myFilledPDF) { pdfreader = new PdfReader(myFilledPDF.Buffer); myPDF = new ByteBuffer(); pdfStamper = new PdfStamper(pdfreader, myPDF); pdfFormFields = pdfStamper.AcroFields; }
/// <summary> /// uses itextsharp 4.1.6 to convert any pdf to 1.4 compatible pdf, called instead of PdfReader.open /// </summary> public static PdfDocument Open(MemoryStream sourceStream, string password = null) { PdfDocument outDoc; sourceStream.Position = 0; var mode = PdfDocumentOpenMode.Modify; try { outDoc = PdfReader.Open(sourceStream, mode); } catch (PdfReaderException) { sourceStream.Position = 0; var outputStream = new MemoryStream(); var reader = password == null ? new TextSharp.PdfReader(sourceStream) : new TextSharp.PdfReader(sourceStream, Encoding.UTF8.GetBytes(password)); var pdfStamper = new iTextSharp.text.pdf.PdfStamper(reader, outputStream) { FormFlattening = true }; pdfStamper.Writer.SetPdfVersion(iTextSharp.text.pdf.PdfWriter.PDF_VERSION_1_4); pdfStamper.Writer.CloseStream = false; pdfStamper.Close(); outDoc = PdfReader.Open(outputStream, mode); } return outDoc; }
/// <summary> /// Fills out and flattens a form with the name, company and country. /// </summary> /// <param name="src"> the path to the original form </param> /// <param name="dest"> the path to the filled out form </param> public void ManipulatePdf(String src, String dest) { PdfReader reader = new PdfReader(src); PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create)); // create? int n = reader.NumberOfPages; Rectangle pagesize; for (int i = 1; i <= n; i++) { PdfContentByte under = stamper.GetUnderContent(i); pagesize = reader.GetPageSize(i); float x = (pagesize.Left + pagesize.Right)/2; float y = (pagesize.Bottom + pagesize.Top)/2; PdfGState gs = new PdfGState(); gs.FillOpacity = 0.3f; under.SaveState(); under.SetGState(gs); under.SetRGBColorFill(200, 200, 0); ColumnText.ShowTextAligned(under, Element.ALIGN_CENTER, new Phrase("Watermark", new Font(Font.FontFamily.HELVETICA, 120)), x, y, 45); under.RestoreState(); } stamper.Close(); reader.Close(); }
// --------------------------------------------------------------------------- /** * Manipulates a PDF file src with the file dest as result * @param src the original PDF */ public byte[] ManipulatePdf(byte[] src) { PdfReader reader = new PdfReader(src); using (MemoryStream ms = new MemoryStream()) { using (PdfStamper stamper = new PdfStamper(reader, ms)) { AcroFields form = stamper.AcroFields; form.SetField("choice_1", "NL"); form.SetListSelection("choice_2", new String[]{"German", "Spanish"}); String[] languages = form.GetListOptionDisplay("choice_3"); String[] exportvalues = form.GetListOptionExport("choice_3"); int n = languages.Length; String[] new_languages = new String[n + 2]; String[] new_exportvalues = new String[n + 2]; for (int i = 0; i < n; i++) { new_languages[i] = languages[i]; new_exportvalues[i] = exportvalues[i]; } new_languages[n] = "Chinese"; new_exportvalues[n] = "CN"; new_languages[n + 1] = "Japanese"; new_exportvalues[n + 1] = "JP"; form.SetListOption("choice_3", new_exportvalues, new_languages); form.SetField("choice_3", "CN"); form.SetField("choice_4", "Japanese"); } return ms.ToArray(); } }
//Permite cargar en un PDF información en los formularios preestablecidos. public void llenarFormulario(string archivoOrigen, string archivoFinal, string dato) { //Establece el archivo de entrada y de salida. string pdfTemplate = archivoOrigen; string newFile = archivoFinal; PdfReader pdfReader = new PdfReader(pdfTemplate); PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.OpenOrCreate)); AcroFields pdfFormFields = pdfStamper.AcroFields; // Asigna los campos pdfFormFields.SetField("Colono", dato); //Muestra mensaje. //MessageBox.Show(sTmp, "Terminado"); // Cambia la propiedad para que no se pueda editar el PDF pdfStamper.FormFlattening = true; pdfStamper.FreeTextFlattening = true; pdfStamper.Writer.CloseStream = true; pdfStamper.Close(); // Cierra el PDF pdfStamper.Close(); pdfReader.Close(); }
// --------------------------------------------------------------------------- /** * Manipulates a PDF file src with the file dest as result * @param src the original PDF */ public override byte[] ManipulatePdf(byte[] src) { locations = PojoFactory.GetLocations(); // Create a reader PdfReader reader = new PdfReader(src); using (MemoryStream ms = new MemoryStream()) { // Create a stamper using (PdfStamper stamper = new PdfStamper(reader, ms)) { // Add annotations for every screening int page = 1; Rectangle rect; PdfAnnotation annotation; foreach (string day in PojoFactory.GetDays()) { foreach (Screening screening in PojoFactory.GetScreenings(day)) { rect = GetPosition(screening); annotation = PdfAnnotation.CreateLink( stamper.Writer, rect, PdfAnnotation.HIGHLIGHT_INVERT, new PdfAction(string.Format(IMDB, screening.movie.Imdb)) ); stamper.AddAnnotation(annotation, page); } page++; } } return ms.ToArray(); } }
public async Task<byte[]> Create(Invoice invoice) { var formBytes = await GetInvoiceFormAsync(); byte[] output = null; using (var rdr = new PdfReader(formBytes)) { var outputStream = new MemoryStream(); using (var stamper = new PdfStamper(rdr, outputStream)) { stamper.FormFlattening = true; stamper.AcroFields.SetField("StartDate", invoice.StartDateTime.ToString("yyyy-MM-dd")); stamper.AcroFields.SetField("EndAddress", invoice.EndAddress); stamper.AcroFields.SetField("StartAddress", invoice.StartAddress); stamper.AcroFields.SetField("Cost", invoice.Cost.ToString()); stamper.AcroFields.SetField("Distance", String.Format("{0} miles", invoice.Distance.ToString())); stamper.AcroFields.SetField("Duration", String.Format("{0}''", invoice.Duration.ToString())); stamper.AcroFields.SetField("EmployeeName", invoice.EmployeeName); stamper.AcroFields.SetField("SignatureName", invoice.EmployeeName); stamper.AcroFields.SetField("StartTime", invoice.StartDateTime.ToString("HH:mm:ss tt")); stamper.AcroFields.SetField("Signature", Convert.ToBase64String(invoice.Signature)); } output = (Byte[])outputStream.ToArray(); } return output; }
// --------------------------------------------------------------------------- /** * Manipulates a PDF file src * @param src the original PDF */ public byte[] ManipulatePdf(byte[] src) { PdfReader reader = new PdfReader(src); PdfObject obj; PdfDictionary action; for (int i = 1; i < reader.XrefSize; i++) { obj = reader.GetPdfObject(i); if (obj is PdfDictionary) { action = ((PdfDictionary)obj).GetAsDict(PdfName.A); if (action == null) continue; if (PdfName.LAUNCH.Equals(action.GetAsName(PdfName.S))) { action.Remove(PdfName.F); action.Remove(PdfName.WIN); action.Put(PdfName.S, PdfName.JAVASCRIPT); action.Put(PdfName.JS, new PdfString( "app.alert('Launch Application Action removed by iText');\r" )); } } } using (MemoryStream ms = new MemoryStream()) { using (PdfStamper stamper = new PdfStamper(reader, ms)) { } return ms.ToArray(); } }
// --------------------------------------------------------------------------- /** * Renames the fields in an interactive form. * @param datasheet the path to the original form * @param i a number that needs to be appended to the field names * @return a byte[] containing an altered PDF file */ private static byte[] RenameFieldsIn(string datasheet, int i) { List<string> form_keys = new List<string>(); using (var ms = new MemoryStream()) { PdfReader reader = new PdfReader(datasheet); // Create the stamper using (PdfStamper stamper = new PdfStamper(reader, ms)) { // Get the fields AcroFields form = stamper.AcroFields; // so we aren't hit with 'Collection was modified' exception foreach (string k in stamper.AcroFields.Fields.Keys) { form_keys.Add(k); } // Loop over the fields foreach (string key in form_keys) { // rename the fields form.RenameField(key, string.Format("{0}_{1}", key, i)); } } reader.Close(); return ms.ToArray(); } }
// --------------------------------------------------------------------------- /** * Manipulates a PDF file src with the file dest as result * @param src the original PDF */ public byte[] ManipulatePdf(byte[] src) { // Create a reader PdfReader reader = new PdfReader(src); using (MemoryStream ms = new MemoryStream()) { // Create a stamper using (PdfStamper stamper = new PdfStamper(reader, ms)) { Image img; float x = 11.5f; float y = 769.7f; float llx, lly, urx, ury; string RESOURCE = Utility.ResourcePosters; // Loop over all the movies to add a popup annotation foreach (Movie movie in PojoFactory.GetMovies()) { img = Image.GetInstance(Path.Combine(RESOURCE, movie.Imdb + ".jpg")); img.ScaleToFit(1000, 60); llx = x + (45 - img.ScaledWidth) / 2; lly = y; urx = x + img.ScaledWidth; ury = y + img.ScaledHeight; AddPopup(stamper, new Rectangle(llx, lly, urx, ury), movie.MovieTitle, string.Format(INFO, movie.Year, movie.Duration), movie.Imdb ); x += 48; if (x > 578) { x = 11.5f; y -= 84.2f; } } } return ms.ToArray(); } }
// --------------------------------------------------------------------------- /** * Manipulates a PDF file src with the file dest as result * @param src the original PDF */ public byte[] ManipulatePdf(byte[] src) { // Create a list with bookmarks List<Dictionary<string, object>> outlines = new List<Dictionary<string, object>>(); Dictionary<string, object> map = new Dictionary<string, object>(); outlines.Add(map); map.Add("Title", "Calendar"); List<Dictionary<string, object>> kids = new List<Dictionary<string, object>>(); map.Add("Kids", kids); int page = 1; IEnumerable<string> days = PojoFactory.GetDays(); foreach (string day in days) { Dictionary<string, object> kid = new Dictionary<string, object>(); kids.Add(kid); kid["Title"] = day; kid["Action"] = "GoTo"; kid["Page"] = String.Format("{0} Fit", page++); } // Create a reader PdfReader reader = new PdfReader(src); using (MemoryStream ms = new MemoryStream()) { // Create a stamper using (PdfStamper stamper = new PdfStamper(reader, ms)) { stamper.Outlines = outlines; } return ms.ToArray(); } }
public static void WritePDF(string outFilename, Dictionary<string, string> keys) { using (var existingFileStream = new FileStream(DefaultTemplatePath, FileMode.Open)) using (var newFileStream = new FileStream(outFilename, FileMode.Create)) { var pdfReader = new PdfReader(existingFileStream); var stamper = new PdfStamper(pdfReader, newFileStream); try { var form = stamper.AcroFields; var fieldKeys = form.Fields.Keys; //File.WriteAllLines(@"fields.txt", fieldKeys.OfType<string>().ToArray()); foreach (string fieldKey in fieldKeys) { if (keys.ContainsKey(fieldKey)) { form.SetField(fieldKey, keys[fieldKey]); } } stamper.FormFlattening = true; } finally { stamper.Close(); pdfReader.Close(); } } }
public bool WatermarkPDF_SW(string SourcePdfPath, string OutputPdfPath, string WatermarkImageUrl, int positionX, int positionY, int WatermarkHeight, int WatermarkWidth, out string msg) { try { PdfReader reader = new PdfReader(SourcePdfPath); PdfStamper stamp = new PdfStamper(reader, new FileStream(OutputPdfPath, FileMode.Create)); int n = reader.NumberOfPages; int i = 0; PdfContentByte under; WatermarkWidth = WatermarkWidth / n; //����ط�Ҫע�⣬�Ǹ���ҳ������̬����ͼƬ��ַ���м�ҳ�ͼ��ؼ�ҳ��ͼƬ string WatermarkPath = Server.MapPath(Request.ApplicationPath + "/HTProject/Pages/Images/��ͬ��������" + n + "/"); string WatermarkPath2 = ""; while (i < n) { i++; WatermarkPath2 = WatermarkPath + i + ".gif"; iTextSharp.text.Image im = iTextSharp.text.Image.GetInstance(WatermarkPath2); im.SetAbsolutePosition(positionX, positionY); im.ScaleAbsolute(WatermarkWidth, WatermarkHeight); under = stamp.GetUnderContent(i); under.AddImage(im, true); } stamp.Close(); reader.Close(); } catch (Exception ex) { msg = ex.Message; return false; } msg = "��ˮӡ�ɹ���"; return true; }
public static void WritePdf(Character character, string pathToPdf) { using (Stream stream = typeof(Functions).Assembly.GetManifestResourceStream("CharDown.CharacterSheet.pdf")) { var pdfReader = new PdfReader(stream); var pdfStamper = new PdfStamper(pdfReader, new FileStream(pathToPdf, FileMode.Create)); var fields = pdfStamper.AcroFields; fields.SetField("CharacterName", character.CharacterName); fields.SetField("STR", character.Strength); fields.SetField("STRmod", character.StrengthModifier); fields.SetField("DEX", character.Dexterity); fields.SetField("DEXmod ", character.DexterityModifier); fields.SetField("CON", character.Constitution); fields.SetField("CONmod", character.ConstitutionModifier); fields.SetField("INT", character.Intelligence); fields.SetField("INTmod", character.IntelligenceModifier); fields.SetField("WIS", character.Wisdom); fields.SetField("WISmod", character.WisdomModifier); fields.SetField("CHA", character.Charisma); fields.SetField("CHamod", character.CharismaModifier); pdfStamper.Close(); } }
// --------------------------------------------------------------------------- public virtual void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { // Get the movies IEnumerable<Movie> movies = PojoFactory.GetMovies(); string datasheet = Path.Combine(Utility.ResourcePdf, DATASHEET); string className = this.ToString(); // Fill out the data sheet form with data foreach (Movie movie in movies) { if (movie.Year < 2007) continue; PdfReader reader = new PdfReader(datasheet); string dest = string.Format(RESULT, movie.Imdb); using (MemoryStream ms = new MemoryStream()) { using (PdfStamper stamper = new PdfStamper(reader, ms)) { AcroFields fields = stamper.AcroFields; fields.GenerateAppearances = true; Fill(fields, movie); if (movie.Year == 2007) stamper.FormFlattening = true; } zip.AddEntry(dest, ms.ToArray()); } } zip.AddFile(datasheet, ""); zip.Save(stream); } }
private static void ApplyWaterMark(string filePath) { Logger.LogI("ApplyWatermark -> " + filePath); var watermarkedFile = Path.GetFileNameWithoutExtension(filePath) + "-w.pdf"; using (var reader1 = new PdfReader(filePath)) { using (var fs = new FileStream(watermarkedFile, FileMode.Create, FileAccess.Write, FileShare.None)) using (var stamper = new PdfStamper(reader1, fs)) { var pageCount = reader1.NumberOfPages; var layer = new PdfLayer("WatermarkLayer", stamper.Writer); for (var i = 1; i <= pageCount; i++) { var rect = reader1.GetPageSize(i); var cb = stamper.GetUnderContent(i); cb.BeginLayer(layer); cb.SetFontAndSize(BaseFont.CreateFont( BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 50); var gState = new PdfGState {FillOpacity = 0.25f}; cb.SetGState(gState); cb.SetColorFill(BaseColor.BLACK); cb.BeginText(); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "(c)2015 ScrapEra", rect.Width/2, rect.Height/2, 45f); cb.EndText(); cb.EndLayer(); } } } File.Delete(filePath); }
public void GenerateCertificateDocument(string targetFilename) { PdfReader reader = new PdfReader(_templateFilename); using (PdfStamper stamper = new PdfStamper(reader, new FileStream(targetFilename, FileMode.Create))) { AcroFields form = stamper.AcroFields; var fieldKeys = form.Fields.Keys; foreach (string fieldKey in fieldKeys) { if (fieldKey.Contains("issuedto1")) form.SetField(fieldKey, Name[0]); if (fieldKey.Contains("issuedto2")) form.SetField(fieldKey, Name[1]); if (fieldKey.Contains("certificatenumber")) form.SetField(fieldKey, CertificateId); if (fieldKey.Contains("registeredtrack")) form.SetField(fieldKey, RegisteredTrack); if (fieldKey.Contains("registrationdate")) form.SetField(fieldKey, RegistrationDate); if (fieldKey.Contains("expirationdate")) form.SetField(fieldKey, ExpirationDate); if (fieldKey.Contains("collaborators")) form.SetField(fieldKey, Collaborators); if (fieldKey.Contains("agent")) form.SetField(fieldKey, Agent); } stamper.FormFlattening = true; } }
// --------------------------------------------------------------------------- /** * Manipulates a PDF file src with the file dest as result * @param src the original PDF */ public byte[] ManipulatePdf(byte[] src) { // Create the reader PdfReader reader = new PdfReader(src); int n = reader.NumberOfPages; using (MemoryStream ms = new MemoryStream()) { // Create the stamper using (PdfStamper stamper = new PdfStamper(reader, ms)) { // Make a list with all the possible actions actions = new List<PdfAction>(); PdfDestination d; for (int i = 0; i < n; ) { d = new PdfDestination(PdfDestination.FIT); actions.Add(PdfAction.GotoLocalPage(++i, d, stamper.Writer)); } // Add a navigation table to every page PdfContentByte canvas; for (int i = 0; i < n; ) { canvas = stamper.GetOverContent(++i); CreateNavigationTable(i, n).WriteSelectedRows(0, -1, 696, 36, canvas); } } return ms.ToArray(); } }
public void FillForm( Dictionary<string, string> items, Stream formStream) { PdfStamper pdfStamper = new PdfStamper(pdfReader, formStream); AcroFields pdfFormFields = pdfStamper.AcroFields; BaseFont arialBaseFont; string arialFontPath; try { arialFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF"); arialBaseFont = BaseFont.CreateFont(arialFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); } catch (IOException) { arialFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIAL.TTF"); arialBaseFont = BaseFont.CreateFont(arialFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); } pdfFormFields.AddSubstitutionFont(arialBaseFont); foreach (KeyValuePair<string, string> item in items) { pdfFormFields.SetFieldProperty(item.Key, "textfont", arialBaseFont, null); if (item.Value!=null) pdfFormFields.SetField(item.Key, item.Value); } pdfStamper.FormFlattening = false; pdfStamper.Close(); }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { Stationery s = new Stationery(); StampStationery ss = new StampStationery(); byte[] stationery = s.CreateStationary(); byte[] sStationery = ss.ManipulatePdf( ss.CreatePdf(), stationery ); byte[] insertPages = ManipulatePdf(sStationery, stationery); zip.AddEntry(RESULT1, insertPages); // reorder the pages in the PDF PdfReader reader = new PdfReader(insertPages); reader.SelectPages("3-41,1-2"); using (MemoryStream ms = new MemoryStream()) { using (PdfStamper stamper = new PdfStamper(reader, ms)) { } zip.AddEntry(RESULT2, ms.ToArray()); } zip.AddEntry(Utility.ResultFileName(s.ToString() + ".pdf"), stationery); zip.AddEntry(Utility.ResultFileName(ss.ToString() + ".pdf"), sStationery); zip.Save(stream); } }
// --------------------------------------------------------------------------- public void Write(Stream stream) { using (ZipFile zip = new ZipFile()) { // Use previous examples to create PDF files MovieLinks1 m = new MovieLinks1(); byte[] pdfM = Utility.PdfBytes(m); LinkActions l = new LinkActions(); byte[] pdfL = l.CreatePdf(); // Create readers. PdfReader[] readers = { new PdfReader(pdfL), new PdfReader(pdfM) }; // step 1 //Document document = new Document(); // step 2 using (var ms = new MemoryStream()) { // step 1 using (Document document = new Document()) { using (PdfCopy copy = new PdfCopy(document, ms)) { // step 3 document.Open(); // step 4 int n; // copy the pages of the different PDFs into one document for (int i = 0; i < readers.Length; i++) { readers[i].ConsolidateNamedDestinations(); n = readers[i].NumberOfPages; for (int page = 0; page < n; ) { copy.AddPage(copy.GetImportedPage(readers[i], ++page)); } } // Add named destination copy.AddNamedDestinations( // from the second document SimpleNamedDestination.GetNamedDestination(readers[1], false), // using the page count of the first document as offset readers[0].NumberOfPages ); } zip.AddEntry(RESULT1, ms.ToArray()); } // Create a reader PdfReader reader = new PdfReader(ms.ToArray()); // Convert the remote destinations into local destinations reader.MakeRemoteNamedDestinationsLocal(); using (MemoryStream ms2 = new MemoryStream()) { // Create a new PDF containing the local destinations using (PdfStamper stamper = new PdfStamper(reader, ms2)) { } zip.AddEntry(RESULT2, ms2.ToArray()); } } zip.AddEntry(Utility.ResultFileName(m.ToString() + ".pdf"), pdfM); zip.AddEntry(Utility.ResultFileName(l.ToString() + ".pdf"), pdfL); zip.Save(stream); } }
// --------------------------------------------------------------------------- /** * Manipulates a PDF file src with the file dest as result * @param src the original PDF */ public virtual byte[] ManipulatePdf(byte[] src) { locations = PojoFactory.GetLocations(); // Create a reader PdfReader reader = new PdfReader(src); using (MemoryStream ms = new MemoryStream()) { // Create a stamper using (PdfStamper stamper = new PdfStamper(reader, ms)) { // Add the annotations int page = 1; Rectangle rect; PdfAnnotation annotation; Movie movie; foreach (string day in PojoFactory.GetDays()) { foreach (Screening screening in PojoFactory.GetScreenings(day)) { movie = screening.movie; rect = GetPosition(screening); annotation = PdfAnnotation.CreateText( stamper.Writer, rect, movie.MovieTitle, string.Format(INFO, movie.Year, movie.Duration), false, "Help" ); annotation.Color = WebColors.GetRGBColor( "#" + movie.entry.category.color ); stamper.AddAnnotation(annotation, page); } page++; } } return ms.ToArray(); } }
internal Boolean DecryptFile( string inputFile, string outputFile, IEnumerable<string> userPasswords) { foreach (var pwd in userPasswords) { try { using (var reader = new PdfReader(inputFile, new ASCIIEncoding().GetBytes(pwd))) { reader.GetType().Field("encrypted").SetValue(reader, false); using (var outStream = File.OpenWrite(outputFile)) { using (var stamper = new PdfStamper(reader, outStream)) { stamper.Close(); } } } return true; } catch (Exception ex) { Logger.ErrorFormat(ex, "Error trying to decrypt file {0}: {1}", inputFile, ex.Message); } } return false; }
public byte[] FillIRS941Form(ReportPayrollCompanyTotal payrollData) { string iRS941FormTemplate = HttpContext.Current.Server.MapPath("~/FormTemplates/IRS2015Form941.pdf"); byte[] formResults; using (PdfReader pdfReader = new PdfReader(iRS941FormTemplate)) { using (MemoryStream ms = new MemoryStream()) { using (PdfStamper pdfStamper = new PdfStamper(pdfReader, ms)) { AcroFields pdfFormFields = pdfStamper.AcroFields; var s = pdfFormFields.GetSignatureNames(); var e = pdfFormFields.GetBlankSignatureNames(); pdfFormFields.SetField("f1_10_0_", "Suitland Road Baptist Church"); pdfStamper.FormFlattening = false; pdfStamper.Close(); } formResults = ms.GetBuffer(); } } return formResults; }
public bool WatermarkPDF_SN(string SourcePdfPath, string OutputPdfPath, string WatermarkPath, int positionX, int positionY, int WatermarkHeight, int WatermarkWidth, out string msg) { try { PdfReader reader = new PdfReader(SourcePdfPath); PdfStamper stamp = new PdfStamper(reader, new FileStream(OutputPdfPath, FileMode.Create)); int n = reader.NumberOfPages; int i = 0; PdfContentByte under; iTextSharp.text.Image im = iTextSharp.text.Image.GetInstance(WatermarkPath); im.SetAbsolutePosition(positionX, positionY); im.ScaleAbsolute(WatermarkWidth, WatermarkHeight); while (i < n) { i++; under = stamp.GetUnderContent(i); under.AddImage(im, true); } stamp.Close(); reader.Close(); } catch (Exception ex) { msg = ex.Message; return false; } msg = "��ˮӡ�ɹ���"; return true; }
// samples taken from // http://www.c-sharpcorner.com/uploadfile/scottlysle/pdfgenerator_cs06162007023347am/pdfgenerator_cs.aspx // http://blog.codecentric.de/en/2010/08/pdf-generation-with-itext/ public string SetFields(string PathSource, string PathTarget, System.Object myFields) { try { GeneXus.Utils.GXProperties Fields = (GeneXus.Utils.GXProperties)myFields; // create a new PDF reader based on the PDF template document iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(PathSource); iTextSharp.text.pdf.PdfStamper pdfStamper = new iTextSharp.text.pdf.PdfStamper(pdfReader, new System.IO.FileStream(PathTarget, System.IO.FileMode.Create)); GeneXus.Utils.GxKeyValuePair item = Fields.GetFirst(); while (item != null) { pdfStamper.AcroFields.SetField(item.Key, item.Value); item = Fields.GetNext(); } // flatten the form to remove editting options, set it to false to leave the form open to subsequent manual edits pdfStamper.FormFlattening = false; // close the pdf pdfStamper.Close(); pdfReader.Close(); return(""); } catch (Exception e) { return(e.Message); } }
public string AddSignature(string PathSource, string PathTarget, string CertPath, string CertPass, int lx = 100, int ly = 100, int ux = 250, int uy = 150, int page = 1, bool Visible = true) { try { Org.BouncyCastle.Crypto.AsymmetricKeyParameter Akp = null; Org.BouncyCastle.X509.X509Certificate[] Chain = null; string alias = null; Org.BouncyCastle.Pkcs.Pkcs12Store pk12; pk12 = new Org.BouncyCastle.Pkcs.Pkcs12Store(new System.IO.FileStream(CertPath, System.IO.FileMode.Open, System.IO.FileAccess.Read), CertPass.ToCharArray()); IEnumerable aliases = pk12.Aliases; foreach (string aliasTemp in aliases) { alias = aliasTemp; if (pk12.IsKeyEntry(alias)) { break; } } Akp = pk12.GetKey(alias).Key; Org.BouncyCastle.Pkcs.X509CertificateEntry[] ce = pk12.GetCertificateChain(alias); Chain = new Org.BouncyCastle.X509.X509Certificate[ce.Length]; for (int k = 0; k < ce.Length; ++k) { Chain[k] = ce[k].Certificate; } iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(PathSource); iTextSharp.text.pdf.PdfStamper st = iTextSharp.text.pdf.PdfStamper.CreateSignature(reader, new System.IO.FileStream(PathTarget, System.IO.FileMode.Create, System.IO.FileAccess.Write), '\0', null, true); iTextSharp.text.pdf.PdfSignatureAppearance sap = st.SignatureAppearance; if (Visible == true) { page = (page <1 || page> reader.NumberOfPages) ? 1 : page; sap.SetVisibleSignature(new iTextSharp.text.Rectangle(lx, ly, ux, uy), page, null); } sap.CertificationLevel = iTextSharp.text.pdf.PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED; // digital signature - http://itextpdf.com/examples/iia.php?id=222 IExternalSignature es = new PrivateKeySignature(Akp, "SHA-256"); // "BC" MakeSignature.SignDetached(sap, es, new X509Certificate[] { pk12.GetCertificate(alias).Certificate }, null, null, null, 0, CryptoStandard.CMS); st.Close(); return(""); } catch (Exception e) { return(e.Message); } }
protected void Replace_Click(object sender, EventArgs e) { string ReplacingVariable = txtReplace.Text; string sourceFile = "Source File Path"; string descFile = "Destination File Path"; PdfReader pReader = new PdfReader(sourceFile); stamper = new iTextSharp.text.pdf.PdfStamper(pReader, new System.IO.FileStream(descFile, System.IO.FileMode.Create)); PDFTextGetter("ExistingVariableinPDF", ReplacingVariable, StringComparison.CurrentCultureIgnoreCase, sourceFile, descFile); stamper.Close(); pReader.Close(); }
public static void RotatePdf() { var reader = new iTextSharp.text.pdf.PdfReader(@"C:\Projects\31g\trunk\temp\pdf\Europe_565BCE.pdf"); var pageDict = reader.GetPageN(1); pageDict.Put(iTextSharp.text.pdf.PdfName.ROTATE, new iTextSharp.text.pdf.PdfNumber(270)); var stamper = new iTextSharp.text.pdf.PdfStamper(reader, new System.IO.FileStream(@"C:\Projects\31g\trunk\Notes\misc\Maps\Europe_565BCE.pdf", FileMode.Create)); stamper.Close(); reader.Close(); }
public void PDFTextGetter(string pSearch, StringComparison SC, string SourceFile, string DestinationFile) { iTextSharp.text.pdf.PdfStamper stamper = null; iTextSharp.text.pdf.PdfContentByte cb = null; this.Cursor = Cursors.WaitCursor; if (File.Exists(SourceFile)) { PdfReader pReader = new PdfReader(SourceFile); stamper = new iTextSharp.text.pdf.PdfStamper(pReader, new System.IO.FileStream(DestinationFile, FileMode.Create)); PB.Value = 0; PB.Maximum = pReader.NumberOfPages; for (int page = 1; page <= pReader.NumberOfPages; page++) { myLocationTextExtractionStrategy strategy = new myLocationTextExtractionStrategy(); cb = stamper.GetUnderContent(page); //Send some data contained in PdfContentByte, looks like the first is always cero for me and the second 100, but i'm not sure if this could change in some cases strategy.UndercontentCharacterSpacing = cb.CharacterSpacing; strategy.UndercontentHorizontalScaling = cb.HorizontalScaling; //It's not really needed to get the text back, but we have to call this line ALWAYS, //because it triggers the process that will get all chunks from PDF into our strategy Object string currentText = PdfTextExtractor.GetTextFromPage(pReader, page, strategy); //The real getter process starts in the following line List <iTextSharp.text.Rectangle> MatchesFound = strategy.GetTextLocations(pSearch, SC); //Set the fill color of the shapes, I don't use a border because it would make the rect bigger //but maybe using a thin border could be a solution if you see the currect rect is not big enough to cover all the text it should cover cb.SetColorFill(BaseColor.PINK); //MatchesFound contains all text with locations, so do whatever you want with it, this highlights them using PINK color: foreach (iTextSharp.text.Rectangle rect in MatchesFound) { cb.Rectangle(rect.Left, rect.Bottom, rect.Width, rect.Height); } cb.Fill(); PB.Value = PB.Value + 1; } stamper.Close(); pReader.Close(); } this.Cursor = Cursors.Default; }
public HttpResponseMessage UpdatePdfDoc(UpdatePDF updatePDF) { HttpResponseMessage response = null; try { string ExistingVariableinPDF = updatePDF.ExistingVariableinPDF; string ReplacingVariable = updatePDF.ReplacingVariable; string ReplacingDateVariable = updatePDF.ReplacingDateVariable; string sourceFile = @updatePDF.sourceFile; Guid guid = Guid.NewGuid(); FileInfo fileInfo = new FileInfo(sourceFile); string tempfilename = Path.Combine(fileInfo.Directory.FullName, guid.ToString() + fileInfo.Extension); string destFile = @tempfilename; PdfReader pReader = new PdfReader(sourceFile); int numberOfPages = pReader.NumberOfPages; FileStream fileStream = new System.IO.FileStream(destFile, System.IO.FileMode.Create); stamper = new iTextSharp.text.pdf.PdfStamper(pReader, fileStream); PDFTextGetter(ExistingVariableinPDF, ReplacingVariable, StringComparison.CurrentCultureIgnoreCase, sourceFile, destFile); if (!String.IsNullOrEmpty(ReplacingDateVariable)) { PDFTextGetter(ReplacingDateVariable, DateTime.Now.DisplayWithSuffix(), StringComparison.CurrentCultureIgnoreCase, sourceFile, destFile); } stamper.Close(); stamper.Dispose(); pReader.Close(); pReader.Dispose(); fileStream.Close(); fileInfo.Refresh(); File.Delete(sourceFile); response = Request.CreateResponse(System.Net.HttpStatusCode.OK, guid.ToString()); } catch (Exception ex) { response = new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError); Logger.WriteLog("Exception while UpdatePdfDoc " + ex.Message + Environment.NewLine + ex.StackTrace); } // File.Move(tempfilename, sourceFile); return(response); }
private static InsertResult InsertImpl(IInput context, Stream input, int page, PdfImage image, PointF imageOffset, PdfImageStyle style) { var outputStream = new MemoryStream(); try { var reader = new TextSharp.PdfReader(input); var stamper = new TextSharp.PdfStamper(reader, outputStream); var pages = reader.NumberOfPages; for (var pdfPage = 1; pdfPage <= pages; pdfPage++) { if (pdfPage != page) { continue; } var cb = stamper.GetOverContent(pdfPage); image.Image.SetAbsolutePosition(imageOffset.X, imageOffset.Y); cb.AddImage(image.Image); break; } stamper.Close(); reader.Close(); return(InsertResult.CreateSuccessResult(new InsertResultData { Context = context, InputStream = input, OutputStream = new MemoryStream(outputStream.GetBuffer()) })); } catch (Exception ex) { return(InsertResult.FromException( ex, new InsertResultData { Context = context, InputStream = input, OutputStream = input })); } }
} // end setGraphTitle private void AddWatermarkText(string sourceFile, string outputFile, string watermarkText, float watermarkFontSize, float watermarkFontOpacity, float watermarkRotation) { iTextSharp.text.pdf.PdfReader reader = null; iTextSharp.text.pdf.PdfStamper stamper = null; iTextSharp.text.pdf.PdfGState gstate = null; iTextSharp.text.pdf.PdfContentByte underContent = null; iTextSharp.text.Rectangle rect = null; int pageCount = 0; try { reader = new iTextSharp.text.pdf.PdfReader(sourceFile); rect = reader.GetPageSizeWithRotation(1); stamper = new PdfStamper(reader, new System.IO.FileStream(outputFile, System.IO.FileMode.CreateNew), '\0', true); iTextSharp.text.pdf.BaseFont watermarkFont = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.COURIER, iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED); gstate = new iTextSharp.text.pdf.PdfGState(); gstate.FillOpacity = watermarkFontOpacity; gstate.StrokeOpacity = watermarkFontOpacity; pageCount = reader.NumberOfPages; for (int i = 1; i <= pageCount; i++) { underContent = stamper.GetUnderContent(i); underContent.SaveState(); underContent.SetGState(gstate); underContent.SetColorFill(iTextSharp.text.BaseColor.DARK_GRAY); underContent.BeginText(); underContent.SetFontAndSize(watermarkFont, watermarkFontSize); underContent.SetTextMatrix(30, 30); underContent.ShowTextAligned(iTextSharp.text.Element.ALIGN_CENTER, watermarkText, rect.Width / 2, rect.Height / 2, watermarkRotation); underContent.EndText(); underContent.RestoreState(); } // end for i loop stamper.Close(); reader.Close(); } // end try catch (Exception ex) { throw ex; } // end return; } // end AddWatermark
static void ManipulatePdf() { using (var ms = new MemoryStream()) { var pdf = "resources/Project.pdf"; var reader = new iTextSharp.text.pdf.PdfReader(pdf); var stamper = new iTextSharp.text.pdf.PdfStamper(reader, ms); var box = reader.GetCropBox(1); var left = box.Left; var top = box.Top; // var newRectangle = new iTextSharp.text.Rectangle(left + 20, top - 20, left + 250, top - 40); var newRectangle = new iTextSharp.text.Rectangle(left, top, left + 250, top - 40); newRectangle.UseVariableBorders = false; var pcb = new iTextSharp.text.pdf.PdfContentByte(stamper.Writer); pcb.SetColorFill(iTextSharp.text.BaseColor.RED); var text = "Hello, world!"; var annot = iTextSharp.text.pdf.PdfAnnotation.CreateFreeText(stamper.Writer, newRectangle, text, pcb); annot.Flags = iTextSharp.text.pdf.PdfAnnotation.FLAGS_PRINT; // annot.BorderStyle = new iTextSharp.text.pdf.PdfBorderDictionary(0, 0); // annot.Color = GetBaseColor(Color.Yellow); // annot.Put(PdfName.DS, new PdfString("font: " + "Tohama" + " " + // (10 * 0.75f) + "pt; text-align: left; color: " + // GetBaseColor(Color.Blue))); // annot.Put(PdfName.RC, new PdfString(text.Replace("(?i)<br */?> ", "\n").Replace(" & nbsp; ", " "))); // annot.Put(PdfName.ROTATE, new PdfNumber(0)); stamper.AddAnnotation(annot, 1); stamper.Close(); var output = ms.ToArray(); System.IO.File.WriteAllBytes(".output/Hello.pdf", output); } }
void ManipulatePdf(string src, string dest, MetaData md) { using (var reader = new ip.PdfReader(src)) { var catalog = reader.Catalog; var structTreeRoot = catalog.GetAsDict(ip.PdfName.STRUCTTREEROOT); Manipulate(structTreeRoot); using (var stamper = new ip.PdfStamper(reader, new FileStream(dest, FileMode.Create))) { var page = reader.GetPageN(1); using (var ms = new MemoryStream()) { var dic = new ip.PdfDictionary(); DateTime time = DateTime.Now; if (reader.Info.ContainsKey(ip.PdfName.CREATIONDATE.ToString().Substring(1))) { var temp = reader.Info[ip.PdfName.CREATIONDATE.ToString().Substring(1)].Substring(2).Replace('\'', ':'); temp = temp.Substring(0, temp.Length - 1); time = DateTime.ParseExact(temp, "yyyyMMddHHmmsszzz", CultureInfo.InvariantCulture); } dic.Put(ip.PdfName.PRODUCER, new ip.PdfString(md.Creator)); dic.Put(ip.PdfName.TITLE, new ip.PdfString(Path.GetFileNameWithoutExtension(dest))); dic.Put(ip.PdfName.CREATOR, new ip.PdfString(md.Creator)); dic.Put(ip.PdfName.AUTHOR, new ip.PdfString(md.Author)); dic.Put(ip.PdfName.CREATIONDATE, new ip.PdfDate(time)); var xmp = new XmpWriter(ms, dic); xmp.Close(); var reference = stamper.Writer.AddToBody(new ip.PdfStream(ms.ToArray())); page.Put(ip.PdfName.METADATA, reference.IndirectReference); if (ms != null) { var d = Encoding.UTF8.GetString(ms.ToArray()); var xml = new XmlDocument(); xml.LoadXml(d); var node = xml.DocumentElement.FirstChild; node = node.FirstChild; if (node != null) { //node.AppendAttribute("xmlns:pdfaid", "http://www.aiim.org/pdfa/ns/id/"); var attrId = xml.CreateAttribute("xmlns:pdfaid"); attrId.Value = "http://www.aiim.org/pdfa/ns/id/"; node.Attributes.Append(attrId); var attrPart = xml.CreateAttribute("pdfaid:part", "http://www.aiim.org/pdfa/ns/id/"); attrPart.Value = "1"; node.Attributes.Append(attrPart); var attrConf = xml.CreateAttribute("pdfaid:conformance", "http://www.aiim.org/pdfa/ns/id/"); attrConf.Value = "A"; node.Attributes.Append(attrConf); if (md.CustomMetadata != null && md.CustomMetadata.Length > 0) { var dataNode = node.OwnerDocument.CreateElement("CustomMetaData"); node.AppendChild(dataNode); dataNode.InnerText = System.Convert.ToBase64String(md.CustomMetadata); } } ms.Position = 0; xml.Save(ms); d = Encoding.UTF8.GetString(ms.ToArray()); } stamper.XmpMetadata = ms.ToArray(); stamper.Close(); reader.Close(); } } } }
public XfaXmlLocator(PdfStamper stamper) { this.stamper = stamper; CreateXfaForm(); }
/// <summary> /// Assina o arquivo PDF /// </summary> /// <param name="filePath">Caminho do arquivo</param> /// <param name="certificate">Certificado</param> /// <param name="reason">Motivo da assinatura</param> internal static void sign(string filePath, X509Certificate2 certificate, string reason = null) { try { // make the certificate chain IList <BCX.X509Certificate> chain = getCertChain(certificate); // open the original file TS.PdfReader reader = new TS.PdfReader(filePath); string newFilePath = filePath.Substring(0, filePath.Length - 4) + "_signed.pdf"; // create a new file FileStream fout = new FileStream(newFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); // create the "stamp" on the file TS.PdfStamper stamper = TS.PdfStamper.CreateSignature(reader, fout, '\0', null, true); TS.PdfSignatureAppearance appearance = stamper.SignatureAppearance; appearance.Reason = reason; appearance.Location = getLocation(certificate.Subject); int i = 1; int xdiff = 0; while (true) { string fieldName = "Assinatura" + i.ToString();; try { appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(20 + xdiff, 10, 170 + xdiff, 60), 1, fieldName); TSS.X509Certificate2Signature es = new TSS.X509Certificate2Signature(certificate, "SHA-1"); TSS.MakeSignature.SignDetached(appearance, es, chain, null, null, null, 0, TSS.CryptoStandard.CMS); break; } catch (Exception ex) { if (ex.Message != "The field " + fieldName + " already exists.") { throw ex; } else { i++; xdiff += 180; } } } // close the files reader.Close(); fout.Close(); // delete the tmp file e move the new to the right name System.IO.File.Delete(filePath); System.IO.File.Move(newFilePath, filePath); } catch (Exception ex) { throw ex; } }
public byte[] AddSignatureAppearance(byte[] pdfToStamBytes, string stampString) { using (var ms = new MemoryStream()) { try { var imageWidth = 425; var imageHeight = 89; var fontSize = 0; if (stampString.Length > 25) { fontSize = 8; } else { fontSize = 12; } //TODO: Make configurable string path = "emptyPath"; string xsdFileLinux = @"/var/local/lawtrust/configs/signatureFont.ttf"; string xsdFileWindows = @"C:/lawtrust/configs/signatureFont.ttf"; if (File.Exists(xsdFileLinux)) { path = xsdFileLinux; } else if (File.Exists(xsdFileWindows)) { path = xsdFileWindows; } if (!path.Equals("emptyPath")) { var reader = new iTextSharp.text.pdf.PdfReader(pdfToStamBytes); var stamper = new iTextSharp.text.pdf.PdfStamper(reader, ms); var rotation = reader.GetPageRotation(1); var box = reader.GetPageSizeWithRotation(1); var bf = BaseFont.CreateFont(path, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); var pcb = stamper.GetOverContent(1); var f = new Font(bf, fontSize); var p = new Phrase(stampString, f); //TODO: Make coordinates configurable if (rotation == 90) { //landscape ColumnText.ShowTextAligned(pcb, Element.ALIGN_CENTER, p, 740, 10, 0); } else if (rotation == 180) { //normal PDF ColumnText.ShowTextAligned(pcb, Element.ALIGN_CENTER, p, 500, 10, 0); } else if (rotation == 270) { //landscape ColumnText.ShowTextAligned(pcb, Element.ALIGN_CENTER, p, 740, 10, 0); } else { //normal PDF ColumnText.ShowTextAligned(pcb, Element.ALIGN_CENTER, p, 500, 10, 0); } pcb.SaveState(); stamper.Close(); reader.Close(); return(ms.ToArray()); } else { return(null); } } catch (Exception ex) { //need error handling return(null); } } }
//metodo para crear el pdf al vuelo del saef public byte[] FormarPDF(string HTML, string fileName, string Cabecera, string Pie, string Folio, bool nuevo) { PdfConverter pdfConverter = new PdfConverter(); byte[] bPdf = null; byte[] bResp = null; try { pdfConverter.LicenseKey = "f1ROX0dfTk9OTl9KUU9fTE5RTk1RRkZGRg=="; //Header pdfConverter.PdfDocumentOptions.ShowHeader = true; pdfConverter.PdfHeaderOptions.HeaderHeight = 190; pdfConverter.PdfHeaderOptions.HtmlToPdfArea = new HtmlToPdfArea(Cabecera, null); pdfConverter.PdfHeaderOptions.DrawHeaderLine = false; if (nuevo == false) { //pie pdfConverter.PdfFooterOptions.FooterHeight = 100; pdfConverter.PdfFooterOptions.HtmlToPdfArea = new HtmlToPdfArea(Pie, null); pdfConverter.PdfDocumentOptions.ShowFooter = true; pdfConverter.PdfFooterOptions.DrawFooterLine = false; } //poner el numero de paginacion pdfConverter.PdfFooterOptions.TextArea = new TextArea(5, -5, "Página &p; de &P; ", new System.Drawing.Font(new System.Drawing.FontFamily("Arial"), 8, System.Drawing.GraphicsUnit.Point)); pdfConverter.PdfFooterOptions.TextArea.EmbedTextFont = true; pdfConverter.PdfFooterOptions.TextArea.TextAlign = HorizontalTextAlign.Right; pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.Letter; pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal; //margenes pdfConverter.PdfDocumentOptions.LeftMargin = 40; pdfConverter.PdfDocumentOptions.RightMargin = 40; pdfConverter.PdfDocumentOptions.StretchToFit = true; bPdf = pdfConverter.GetPdfBytesFromHtmlString(HTML); if (nuevo) { //metodo para poner el logo de fondo try { string rutaFondo = "https://sistemas.indaabin.gob.mx/ImagenesComunes/nuevoescudo.png"; MemoryStream stream = new MemoryStream(); iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(bPdf); //crear el objeto pdfstamper que se utiliza para agregar contenido adicional al archivo pdf fuente iTextSharp.text.pdf.PdfStamper pdfStamper = new iTextSharp.text.pdf.PdfStamper(pdfReader, stream); //iterar a través de todas las páginas del archivo fuente pdf for (int pageIndex = 1; pageIndex <= pdfReader.NumberOfPages; pageIndex++) { PdfContentByte overContent = pdfStamper.GetOverContent(pageIndex); iTextSharp.text.Image jpeg = iTextSharp.text.Image.GetInstance(rutaFondo); overContent.SaveState(); overContent.SetGState(new PdfGState { FillOpacity = 0.3f, StrokeOpacity = 0.3f//0.3 }); overContent.AddImage(jpeg, 560f, 0f, 0f, 820f, 0f, 0f); overContent.RestoreState(); } //cerrar stamper y filestream de salida pdfStamper.Close(); stream.Close(); pdfReader.Close(); bResp = stream.ToArray(); pdfStamper = null; pdfReader = null; stream = null; } catch (Exception ex) { } } HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "application/pdf"; HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=Acessibilidad" + " " + fileName + " " + Folio + ".pdf"); if (nuevo) { HttpContext.Current.Response.BinaryWrite(bResp); } else { HttpContext.Current.Response.BinaryWrite(bPdf); } HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); } catch (Exception ex) { } return(bPdf); //return bPdf; }
public String Compare(String outPath, String differenceImagePrefix, Dictionary <int, List <Rectangle> > ignoredAreas) { if (gsExec == null || !File.Exists(gsExec)) { return(undefinedGsPath); } try { DirectoryInfo targetDir; FileSystemInfo[] allImageFiles; FileSystemInfo[] imageFiles; FileSystemInfo[] cmpImageFiles; if (Directory.Exists(outPath)) { targetDir = new DirectoryInfo(outPath); allImageFiles = targetDir.GetFileSystemInfos("*.png"); imageFiles = Array.FindAll(allImageFiles, PngPredicate); foreach (FileSystemInfo fileSystemInfo in imageFiles) { fileSystemInfo.Delete(); } cmpImageFiles = Array.FindAll(allImageFiles, CmpPngPredicate); foreach (FileSystemInfo fileSystemInfo in cmpImageFiles) { fileSystemInfo.Delete(); } } else { targetDir = Directory.CreateDirectory(outPath); } if (File.Exists(outPath + differenceImagePrefix)) { File.Delete(outPath + differenceImagePrefix); } if (ignoredAreas != null && ignoredAreas.Count > 0) { PdfReader cmpReader = new PdfReader(cmpPdf); PdfReader outReader = new PdfReader(outPdf); PdfStamper outStamper = new PdfStamper(outReader, new FileStream(outPath + ignoredAreasPrefix + outPdfName, FileMode.Create)); PdfStamper cmpStamper = new PdfStamper(cmpReader, new FileStream(outPath + ignoredAreasPrefix + cmpPdfName, FileMode.Create)); foreach (KeyValuePair <int, List <Rectangle> > entry in ignoredAreas) { int pageNumber = entry.Key; List <Rectangle> rectangles = entry.Value; if (rectangles != null && rectangles.Count > 0) { PdfContentByte outCB = outStamper.GetOverContent(pageNumber); PdfContentByte cmpCB = cmpStamper.GetOverContent(pageNumber); foreach (Rectangle rect in rectangles) { rect.BackgroundColor = BaseColor.BLACK; outCB.Rectangle(rect); cmpCB.Rectangle(rect); } } } outStamper.Close(); cmpStamper.Close(); outReader.Close(); cmpReader.Close(); init(outPath + ignoredAreasPrefix + outPdfName, outPath + ignoredAreasPrefix + cmpPdfName); } String gsParams = this.gsParams.Replace("<outputfile>", outPath + cmpImage).Replace("<inputfile>", cmpPdf); Process p = new Process(); p.StartInfo.FileName = @gsExec; p.StartInfo.Arguments = @gsParams; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardError = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.CreateNoWindow = true; p.Start(); String line; while ((line = p.StandardOutput.ReadLine()) != null) { Console.Out.WriteLine(line); } p.StandardOutput.Close();; while ((line = p.StandardError.ReadLine()) != null) { Console.Out.WriteLine(line); } p.StandardError.Close(); p.WaitForExit(); if (p.ExitCode == 0) { gsParams = this.gsParams.Replace("<outputfile>", outPath + outImage).Replace("<inputfile>", outPdf); p = new Process(); p.StartInfo.FileName = @gsExec; p.StartInfo.Arguments = @gsParams; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardError = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.CreateNoWindow = true; p.Start(); while ((line = p.StandardOutput.ReadLine()) != null) { Console.Out.WriteLine(line); } p.StandardOutput.Close();; while ((line = p.StandardError.ReadLine()) != null) { Console.Out.WriteLine(line); } p.StandardError.Close(); p.WaitForExit(); if (p.ExitCode == 0) { allImageFiles = targetDir.GetFileSystemInfos("*.png"); imageFiles = Array.FindAll(allImageFiles, PngPredicate); cmpImageFiles = Array.FindAll(allImageFiles, CmpPngPredicate); bool bUnexpectedNumberOfPages = imageFiles.Length != cmpImageFiles.Length; int cnt = Math.Min(imageFiles.Length, cmpImageFiles.Length); if (cnt < 1) { return("No files for comparing!!!\nThe result or sample pdf file is not processed by GhostScript."); } Array.Sort(imageFiles, new ImageNameComparator()); Array.Sort(cmpImageFiles, new ImageNameComparator()); String differentPagesFail = null; for (int i = 0; i < cnt; i++) { Console.Out.WriteLine("Comparing page " + (i + 1).ToString() + " (" + imageFiles[i].FullName + ")..."); FileStream is1 = new FileStream(imageFiles[i].FullName, FileMode.Open); FileStream is2 = new FileStream(cmpImageFiles[i].FullName, FileMode.Open); bool cmpResult = CompareStreams(is1, is2); is1.Close(); is2.Close(); if (!cmpResult) { if (File.Exists(compareExec)) { String compareParams = this.compareParams.Replace("<image1>", imageFiles[i].FullName).Replace("<image2>", cmpImageFiles[i].FullName).Replace("<difference>", outPath + differenceImagePrefix + (i + 1).ToString() + ".png"); p = new Process(); p.StartInfo.FileName = @compareExec; p.StartInfo.Arguments = @compareParams; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = true; p.Start(); while ((line = p.StandardError.ReadLine()) != null) { Console.Out.WriteLine(line); } p.StandardError.Close(); p.WaitForExit(); if (p.ExitCode == 0) { if (differentPagesFail == null) { differentPagesFail = differentPages.Replace("<filename>", outPdf).Replace("<pagenumber>", (i + 1).ToString()); differentPagesFail += "\nPlease, examine " + outPath + differenceImagePrefix + (i + 1).ToString() + ".png for more details."; } else { differentPagesFail = "File " + outPdf + " differs.\nPlease, examine difference images for more details."; } } else { differentPagesFail = differentPages.Replace("<filename>", outPdf).Replace("<pagenumber>", (i + 1).ToString()); Console.Out.WriteLine("Invalid compareExec variable."); } } else { differentPagesFail = differentPages.Replace("<filename>", outPdf).Replace("<pagenumber>", (i + 1).ToString()); differentPagesFail += "\nYou can optionally specify path to ImageMagick compare tool (e.g. -DcompareExec=\"C:/Program Files/ImageMagick-6.5.4-2/compare.exe\") to visualize differences."; break; } } else { Console.Out.WriteLine("done."); } } if (differentPagesFail != null) { return(differentPagesFail); } else { if (bUnexpectedNumberOfPages) { return(unexpectedNumberOfPages.Replace("<filename>", outPdf) + "\n" + differentPagesFail); } } } else { return(gsFailed.Replace("<filename>", outPdf)); } } else { return(gsFailed.Replace("<filename>", cmpPdf)); } } catch (Exception) { return(cannotOpenTargetDirectory.Replace("<filename>", outPdf)); } return(null); }
virtual public void SetStamper(PdfStamper stamper) { this.stamper = stamper; }
/** * The verification constructor * @param stp the PdfStamper to apply the validation to */ internal LtvVerification(PdfStamper stp) { writer = (PdfStamperImp)stp.Writer; reader = stp.Reader; acroFields = stp.AcroFields; }
private string addCompanyLogo(string pdfPath) { string outputPDFPath = null; int clientID = Core.SessionHelper.getClientId(); string logoPath = string.Format("{0}/ClientLogo/{1}.jpg", ConfigurationManager.AppSettings["appPath"].ToString(), clientID); if (File.Exists(logoPath)) { outputPDFPath = string.Format("{0}/Temp/{1}.pdf", appPath, Guid.NewGuid()); using (var inputPdfStream = new FileStream(pdfPath, FileMode.Open)) using (var outputPdfStream = new FileStream(outputPDFPath, FileMode.Create)) { PdfReader reader = new PdfReader(inputPdfStream); PdfStamper stamper = new PdfStamper(reader, outputPdfStream); PdfContentByte pdfContentByte = stamper.GetOverContent(1); //var image = iTextSharp.text.Image.GetInstance(inputImageStream); var image = iTextSharp.text.Image.GetInstance(logoPath); image.ScaleToFit(100f, 100f); PdfDocument doc = pdfContentByte.PdfDocument; image.SetAbsolutePosition(40f, doc.PageSize.Height - 150f); pdfContentByte.AddImage(image); stamper.Close(); } } else { outputPDFPath = pdfPath; } return outputPDFPath; }
// --------------------------------------------------------------------------- /** * Creates a new PDF based on the one in the reader * @param reader a reader with a PDF file */ private byte[] ManipulateWithStamper(PdfReader reader) { using (MemoryStream ms = new MemoryStream()) { using ( PdfStamper stamper = new PdfStamper(reader, ms) ) { } return ms.ToArray(); } }
// --------------------------------------------------------------------------- /** * Manipulates a PDF file src with the file dest as result * @param src the original PDF */ public byte[] ManipulatePdf(byte[] src) { // Create a table with named actions Font symbol = new Font(Font.FontFamily.SYMBOL, 20); PdfPTable table = new PdfPTable(4); table.DefaultCell.Border = Rectangle.NO_BORDER; table.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER; Chunk first = new Chunk( ((char)220).ToString() , symbol); first.SetAction(new PdfAction(PdfAction.FIRSTPAGE)); table.AddCell(new Phrase(first)); Chunk previous = new Chunk( ((char)172).ToString(), symbol); previous.SetAction(new PdfAction(PdfAction.PREVPAGE)); table.AddCell(new Phrase(previous)); Chunk next = new Chunk( ((char)174).ToString(), symbol); next.SetAction(new PdfAction(PdfAction.NEXTPAGE)); table.AddCell(new Phrase(next)); Chunk last = new Chunk( ((char)222).ToString(), symbol); last.SetAction(new PdfAction(PdfAction.LASTPAGE)); table.AddCell(new Phrase(last)); table.TotalWidth = 120; // Create a reader PdfReader reader = new PdfReader(src); using (MemoryStream ms = new MemoryStream()) { // Create a stamper using (PdfStamper stamper = new PdfStamper(reader, ms)) { // Add the table to each page PdfContentByte canvas; for (int i = 0; i < reader.NumberOfPages; ) { canvas = stamper.GetOverContent(++i); table.WriteSelectedRows(0, -1, 696, 36, canvas); } } return ms.ToArray(); } }