public void LayerCheckTest2() { string filename = OUT + "LayerCheckTest2.pdf"; FileStream fos = new FileStream(filename, FileMode.Create); Document document = new Document(); PdfWriter writer = PdfAWriter.GetInstance(document, fos, PdfAConformanceLevel.PDF_A_2B); writer.ViewerPreferences = PdfWriter.PageModeUseOC; writer.PdfVersion = PdfWriter.VERSION_1_5; document.Open(); PdfContentByte cb = writer.DirectContent; PdfLayer nested = new PdfLayer("Nested layers", writer); PdfLayer nested_1 = new PdfLayer("Nested layer 1", writer); PdfLayer nested_2 = new PdfLayer("Nested layer 2", writer); nested.AddChild(nested_1); nested.AddChild(nested_2); writer.LockLayer(nested_2); cb.BeginLayer(nested); Font font = FontFactory.GetFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, true); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("nested layers", font), 50, 775, 0); cb.EndLayer(); cb.BeginLayer(nested_1); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("nested layer 1", font), 100, 800, 0); cb.EndLayer(); cb.BeginLayer(nested_2); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("nested layer 2", font), 100, 750, 0); cb.EndLayer(); document.Close(); }
// =========================================================================== public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); writer.PdfVersion = PdfWriter.VERSION_1_6; // step 3 document.Open(); // step 4 PdfContentByte cb = writer.DirectContent; PdfLayer dog = new PdfLayer("layer 1", writer); PdfLayer tiger = new PdfLayer("layer 2", writer); PdfLayer lion = new PdfLayer("layer 3", writer); PdfLayerMembership cat = new PdfLayerMembership(writer); PdfVisibilityExpression ve1 = new PdfVisibilityExpression( PdfVisibilityExpression.OR ); ve1.Add(tiger); ve1.Add(lion); cat.VisibilityExpression = ve1; PdfLayerMembership no_cat = new PdfLayerMembership(writer); PdfVisibilityExpression ve2 = new PdfVisibilityExpression( PdfVisibilityExpression.NOT ); ve2.Add(ve1); no_cat.VisibilityExpression = ve2; cb.BeginLayer(dog); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("dog"), 50, 775, 0); cb.EndLayer(); cb.BeginLayer(tiger); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("tiger"), 50, 750, 0); cb.EndLayer(); cb.BeginLayer(lion); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("lion"), 50, 725, 0); cb.EndLayer(); cb.BeginLayer(cat); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("cat"), 50, 700, 0); cb.EndLayer(); cb.BeginLayer(no_cat); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("no cat"), 50, 700, 0); cb.EndLayer(); } }
public void LayerCheckTest1() { string filename = OUT + "LayerCheckTest1.pdf"; FileStream fos = new FileStream(filename, FileMode.Create); Document document = new Document(); PdfWriter writer = PdfAWriter.GetInstance(document, fos, PdfAConformanceLevel.PDF_A_2B); writer.ViewerPreferences = PdfWriter.PageModeUseOC; writer.PdfVersion = PdfWriter.VERSION_1_5; document.Open(); PdfLayer layer = new PdfLayer("Do you see me?", writer); layer.On = true; BaseFont bf = BaseFont.CreateFont(RESOURCES + "FreeMonoBold.ttf", BaseFont.WINANSI, true); PdfContentByte cb = writer.DirectContent; cb.BeginText(); cb.SetFontAndSize(bf, 18); cb.ShowTextAligned(Element.ALIGN_LEFT, "Do you see me?", 50, 790, 0); cb.BeginLayer(layer); cb.ShowTextAligned(Element.ALIGN_LEFT, "Peek-a-Boo!!!", 50, 766, 0); cb.EndLayer(); cb.EndText(); document.Close(); }
// --------------------------------------------------------------------------- public byte[] CreatePdf(bool on) { using (MemoryStream ms = new MemoryStream()) { using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, ms); writer.ViewerPreferences = PdfWriter.PageModeUseOC; writer.PdfVersion = PdfWriter.VERSION_1_5; // step 3 document.Open(); // step 4 PdfLayer layer = new PdfLayer("Do you see me?", writer); layer.On = on; BaseFont bf = BaseFont.CreateFont(); PdfContentByte cb = writer.DirectContent; cb.BeginText(); cb.SetFontAndSize(bf, 18); cb.ShowTextAligned(Element.ALIGN_LEFT, "Do you see me?", 50, 790, 0); cb.BeginLayer(layer); cb.ShowTextAligned(Element.ALIGN_LEFT, "Peek-a-Boo!!!", 50, 766, 0); cb.EndLayer(); cb.EndText(); } return(ms.ToArray()); } }
public static void CreatFromTemplate() { string originalFile = "Original.pdf"; string copyOfOriginal = "Copy.pdf"; using (FileStream fs = new FileStream(originalFile, FileMode.Create, FileAccess.Write, FileShare.None)) using (Document doc = new Document(PageSize.LETTER)) using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) { doc.Open(); doc.Add(new Paragraph("Hi! I'm Original")); doc.Close(); } PdfReader reader = new PdfReader(originalFile); using (FileStream fs = new FileStream(copyOfOriginal, FileMode.Create, FileAccess.Write, FileShare.None)) // Creating iTextSharp.text.pdf.PdfStamper object to write // Data from iTextSharp.text.pdf.PdfReader object to FileStream object using (PdfStamper stamper = new PdfStamper(reader, fs)) { // Getting total number of pages of the Existing Document int pageCount = reader.NumberOfPages; // Create New Layer for Watermark PdfLayer layer = new PdfLayer("WatermarkLayer", stamper.Writer); // Loop through each Page for (int i = 1; i <= pageCount; i++) { // Getting the Page Size Rectangle rect = reader.GetPageSize(i); // Get the ContentByte object PdfContentByte cb = stamper.GetUnderContent(i); // Tell the cb that the next commands should be "bound" to this new layer cb.BeginLayer(layer); cb.SetFontAndSize(BaseFont.CreateFont( BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 50); PdfGState gState = new PdfGState(); gState.FillOpacity = 0.25f; cb.SetGState(gState); cb.SetColorFill(BaseColor.BLACK); cb.BeginText(); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "OK COOL A WATERMARK", rect.Width / 2, rect.Height / 2, 45f); cb.EndText(); // Close the layer cb.EndLayer(); } } }
private MemoryStream ApplyVerificationStamp2(byte[] file, string stamp) { var newFile = new MemoryStream(); // Creating watermark on a separate layer // Creating iTextSharp.text.pdf.PdfReader object to read the Existing PDF Document PdfReader reader1 = new PdfReader(file); //using (FileStream fs = new FileStream(watermarkedFile, FileMode.Create, FileAccess.Write, FileShare.None)) // Creating iTextSharp.text.pdf.PdfStamper object to write Data from iTextSharp.text.pdf.PdfReader object to FileStream object using (PdfStamper stamper = new PdfStamper(reader1, newFile)) { // Getting total number of pages of the Existing Document int pageCount = reader1.NumberOfPages; // Create New Layer for Watermark PdfLayer layer = new PdfLayer("WatermarkLayer", stamper.Writer); // Loop through each Page for (int i = 1; i <= pageCount; i++) { // Getting the Page Size Rectangle rect = reader1.GetPageSize(i); // Get the ContentByte object PdfContentByte cb = stamper.GetUnderContent(i); // Tell the cb that the next commands should be "bound" to this new layer cb.BeginLayer(layer); cb.SetFontAndSize(BaseFont.CreateFont( BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 15); PdfGState gState = new PdfGState(); gState.FillOpacity = 0.25f; cb.SetGState(gState); cb.SetColorFill(BaseColor.BLACK); cb.BeginText(); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, stamp, 5, 5, 0); cb.EndText(); // Close the layer cb.EndLayer(); } } return(newFile); }
private void AddWatermark(string pdfloc) { PdfReader reader = new PdfReader(pdfloc); using (FileStream fs = new FileStream("_wtrmked.pdf", FileMode.Create, FileAccess.Write, FileShare.None)) using (PdfStamper stamper = new PdfStamper(reader, fs)) { int pageCount = reader.NumberOfPages; PdfLayer layer = new PdfLayer("WatermarkLayer", stamper.Writer); for (int i = 1; i <= pageCount; i++) { Rectangle rect = reader.GetPageSize(i); PdfContentByte cb = null; if (this.Dispatcher.Invoke(() => dropdown.SelectedValue.ToString() == "Under Content")) { cb = stamper.GetUnderContent(i); } else { cb = stamper.GetOverContent(i); } // Tell the cb that the next commands should be "bound" to this new layer cb.BeginLayer(layer); cb.SetFontAndSize(BaseFont.CreateFont( BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 50); PdfGState gState = new PdfGState(); gState.FillOpacity = 0.25f; cb.SetGState(gState); cb.SetColorFill(BaseColor.BLACK); cb.BeginText(); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, this.Dispatcher.Invoke(() => WtrmkTextbox.Text), rect.Width / 2, rect.Height / 2, 45f); cb.EndText(); // Close the layer cb.EndLayer(); } } reader.Close(); }
/// <summary> /// Adds WaterMark in the PDF. /// </summary> /// <param name="InputFileFullPath"></param> /// <param name="OutputFileFullPath"></param> /// <param name="wWaterMark"></param> public static void AddWaterMark(String InputFileFullPath, String OutputFileFullPath, String wWaterMark) { // Creating watermark on a separate layer // Creating iTextSharp.text.pdf.PdfReader object to read the Existing PDF Document produced by 1 no. PdfReader reader1 = new PdfReader(InputFileFullPath); using (FileStream fs = new FileStream(OutputFileFullPath, FileMode.Create, FileAccess.Write, FileShare.None)) // Creating iTextSharp.text.pdf.PdfStamper object to write Data from iTextSharp.text.pdf.PdfReader object to FileStream object using (PdfStamper stamper = new PdfStamper(reader1, fs)) { // Getting total number of pages of the Existing Document int pageCount = reader1.NumberOfPages; // Create New Layer for Watermark PdfLayer layer = new PdfLayer("WatermarkLayer", stamper.Writer); // Loop through each Page for (int i = 1; i <= pageCount; i++) { // Getting the Page Size iTextSharp.text.Rectangle rect = reader1.GetPageSize(i); // Get the ContentByte object PdfContentByte cb = stamper.GetUnderContent(i); // Tell the cb that the next commands should be "bound" to this new layer cb.BeginLayer(layer); cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED), 50); PdfGState gState = new PdfGState(); gState.FillOpacity = 0.25f; cb.SetGState(gState); cb.SetColorFill(BaseColor.GREEN); cb.BeginText(); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, wWaterMark, rect.Width / 2, rect.Height / 2, 45f); cb.EndText(); // Close the layer cb.EndLayer(); } } }
public void LayerStampingTest() { String outPdf = DestFolder + "out3.pdf"; PdfReader reader = new PdfReader(TestResourceUtils.GetResourceAsStream(TestResourcesPath, "House_Plan_Final.pdf")); PdfStamper stamper = new PdfStamper(reader, File.Create(outPdf)); PdfLayer logoLayer = new PdfLayer("Logos", stamper.Writer); PdfContentByte cb = stamper.GetUnderContent(1); cb.BeginLayer(logoLayer); Image iImage = Image.GetInstance(TestResourceUtils.GetResourceAsStream(TestResourcesPath, "Willi-1.jpg")); iImage.ScalePercent(24f); iImage.SetAbsolutePosition(100, 100); cb.AddImage(iImage); cb.EndLayer(); stamper.Close(); Assert.Null(new CompareTool().CompareByContent(outPdf, TestResourceUtils.GetResourceAsTempFile(TestResourcesPath, "cmp_House_Plan_Final.pdf"), DestFolder, "diff_")); }
public byte[] AgregarImagenAPDF(byte[] bytes, String codigoBarras) { PdfReader reader = null; FileStream fs = null; MemoryStream ms = null; PdfStamper stamper = null; try { // agrego la imagen en una capa separada //creo el objeto reader para leer el documento pdf reader = new PdfReader(bytes); ms = new MemoryStream(); //creo el objeto stamper para escribir datos desde el objeto pdfreader al objeto memorystream/filestream stamper = new PdfStamper(reader, ms); // creo una nueva capa PdfLayer layer = new PdfLayer("Foto", stamper.Writer); // Getting the Page Size //Rectangle rect = reader.GetPageSize(i); // obtengo el objeto ContentByte de la pagina i // int i = 1; int total = reader.NumberOfPages + 1; for (int i = 1; i < total; i++) { //PdfContentByte cb = stamper.GetOverContent(i);//;GetUnderContent(i); PdfContentByte cb = stamper.GetOverContent(i); //Le indico al cb que los proximos comandos seran ligados a esta nueva capa cb.BeginLayer(layer); // cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 50); /* esto es para que aparezca ser una marca de agua */ /* PdfGState gState = new PdfGState(); * gState.FillOpacity = 0.25f; * cb.SetGState(gState);*/ // cb.SetColorFill(BaseColor.BLACK); /* cb.BeginText(); * cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, watermarkText, rect.Width / 2, rect.Height / 2, 45f); * cb.EndText();*/ // Creamos la imagen y le ajustamos el tamaño //iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(rutaFoto); //iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(bytes_img); Barcode128 bc128 = new Barcode128(); bc128.Code = codigoBarras; bc128.Font = null; Image imagen = bc128.CreateImageWithBarcode(cb, null, null); imagen.BorderWidth = 0; imagen.Alignment = Element.ALIGN_TOP; float percentage = 0.0f; percentage = 150 / imagen.Width; imagen.ScaleAbsolute(1.0f, 1.0f); //mismo tamaño imagen.ScalePercent(percentage * 85); //escalo a un 85% //imagen.ScalePercent(100.0f); // 100.0f == same size imagen.SetAbsolutePosition(360, 690); cb.AddImage(imagen); ///aggrego la capa que hace la imagen redonda // iTextSharp.text.Image imagen2 = iTextSharp.text.Image.GetInstance("c:/oie_trans_redim.gif"); //iTextSharp.text.Image imagen2 = iTextSharp.text.Image.GetInstance("c:/oie_trans2.gif"); // imagen2.BorderWidth = 0; // imagen2.Alignment = Element.ALIGN_TOP; // float percentage2 = 0.0f; // percentage2 = 150 / imagen2.Width; // imagen2.ScaleAbsolute(1.0f, 1.0f);//mismo tamaño //imagen.ScalePercent(percentage2 * 100); // imagen2.ScalePercent(100.0f); // 100.0f == same size // imagen2.SetAbsolutePosition(483, 708); // cb.AddImage(imagen2); // Close the layer cb.EndLayer(); // } } int length = Convert.ToInt32(ms.Length); byte[] data = new byte[length]; ms.Read(data, 0, length); // stamper.FormFlattening = true;//para que no se pueda editar el pdf generado stamper.Close(); //cierro el pdf reader.Close(); ms.Close(); byte[] Bytes = ms.ToArray(); return(Bytes); } finally { // Garantizamos que aunque falle se cierran los objetos // alternativa:usar using reader.Close(); if (stamper != null) { stamper.Close(); } if (fs != null) { fs.Close(); } /* if (document != null) document.Close();*/ } }
// =========================================================================== public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); writer.PdfVersion = PdfWriter.VERSION_1_5; // step 3 document.Open(); // step 4 PdfLayer a1 = new PdfLayer("answer 1", writer); PdfLayer a2 = new PdfLayer("answer 2", writer); PdfLayer a3 = new PdfLayer("answer 3", writer); a1.On = false; a2.On = false; a3.On = false; BaseFont bf = BaseFont.CreateFont(); PdfContentByte cb = writer.DirectContent; cb.BeginText(); cb.SetFontAndSize(bf, 18); cb.ShowTextAligned(Element.ALIGN_LEFT, "Q1: Who is the director of the movie 'Paths of Glory'?", 50, 766, 0); cb.ShowTextAligned(Element.ALIGN_LEFT, "Q2: Who directed the movie 'Lawrence of Arabia'?", 50, 718, 0); cb.ShowTextAligned(Element.ALIGN_LEFT, "Q3: Who is the director of 'House of Flying Daggers'?", 50, 670, 0); cb.EndText(); cb.SaveState(); cb.SetRGBColorFill(0xFF, 0x00, 0x00); cb.BeginText(); cb.BeginLayer(a1); cb.ShowTextAligned(Element.ALIGN_LEFT, "A1: Stanley Kubrick", 50, 742, 0); cb.EndLayer(); cb.BeginLayer(a2); cb.ShowTextAligned(Element.ALIGN_LEFT, "A2: David Lean", 50, 694, 0); cb.EndLayer(); cb.BeginLayer(a3); cb.ShowTextAligned(Element.ALIGN_LEFT, "A3: Zhang Yimou", 50, 646, 0); cb.EndLayer(); cb.EndText(); cb.RestoreState(); List <Object> stateOn = new List <Object>(); stateOn.Add("ON"); stateOn.Add(a1); stateOn.Add(a2); stateOn.Add(a3); PdfAction actionOn = PdfAction.SetOCGstate(stateOn, true); List <Object> stateOff = new List <Object>(); stateOff.Add("OFF"); stateOff.Add(a1); stateOff.Add(a2); stateOff.Add(a3); PdfAction actionOff = PdfAction.SetOCGstate(stateOff, true); List <Object> stateToggle = new List <Object>(); stateToggle.Add("Toggle"); stateToggle.Add(a1); stateToggle.Add(a2); stateToggle.Add(a3); PdfAction actionToggle = PdfAction.SetOCGstate(stateToggle, true); Phrase p = new Phrase("Change the state of the answers:"); Chunk on = new Chunk(" on ").SetAction(actionOn); p.Add(on); Chunk off = new Chunk("/ off ").SetAction(actionOff); p.Add(off); Chunk toggle = new Chunk("/ toggle").SetAction(actionToggle); p.Add(toggle); document.Add(p); } }
private void Form1_Load(object sender, EventArgs e) { string workingFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string startFile = Path.Combine(workingFolder, "StartFile.pdf"); string watermarkedFile = Path.Combine(workingFolder, "Watermarked.pdf"); string unwatermarkedFile = Path.Combine(workingFolder, "Un-watermarked.pdf"); string watermarkText = "This is a test"; //SECTION 1 //Create a 5 page PDF, nothing special here using (FileStream fs = new FileStream(startFile, FileMode.Create, FileAccess.Write, FileShare.None)) { using (Document doc = new Document(PageSize.LETTER)) { using (PdfWriter witier = PdfWriter.GetInstance(doc, fs)) { doc.Open(); for (int i = 1; i <= 5; i++) { doc.NewPage(); doc.Add(new Paragraph(String.Format("This is page {0}", i))); } doc.Close(); } } } //SECTION 2 //Create our watermark on a separate layer. The only different here is that we are adding the watermark to a PdfLayer which is an OCG or Optional Content Group PdfReader reader1 = new PdfReader(startFile); using (FileStream fs = new FileStream(watermarkedFile, FileMode.Create, FileAccess.Write, FileShare.None)) { using (PdfStamper stamper = new PdfStamper(reader1, fs)) { int pageCount1 = reader1.NumberOfPages; //Create a new layer PdfLayer layer = new PdfLayer("WatermarkLayer", stamper.Writer); for (int i = 1; i <= pageCount1; i++) { iTextSharp.text.Rectangle rect = reader1.GetPageSize(i); //Get the ContentByte object PdfContentByte cb = stamper.GetUnderContent(i); //Tell the CB that the next commands should be "bound" to this new layer cb.BeginLayer(layer); cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 50); PdfGState gState = new PdfGState(); gState.FillOpacity = 0.25f; cb.SetGState(gState); cb.SetColorFill(BaseColor.BLACK); cb.BeginText(); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, watermarkText, rect.Width / 2, rect.Height / 2, 45f); cb.EndText(); //"Close" the layer cb.EndLayer(); } } } //SECTION 3 //Remove the layer created above //First we bind a reader to the watermarked file, then strip out a bunch of things, and finally use a simple stamper to write out the edited reader PdfReader reader2 = new PdfReader(watermarkedFile); //NOTE, This will destroy all layers in the document, only use if you don't have additional layers //Remove the OCG group completely from the document. //reader2.Catalog.Remove(PdfName.OCPROPERTIES); //Clean up the reader, optional reader2.RemoveUnusedObjects(); //Placeholder variables PRStream stream; String content; PdfDictionary page; PdfArray contentarray; //Get the page count int pageCount2 = reader2.NumberOfPages; //Loop through each page for (int i = 1; i <= pageCount2; i++) { //Get the page page = reader2.GetPageN(i); //Get the raw content contentarray = page.GetAsArray(PdfName.CONTENTS); if (contentarray != null) { //Loop through content for (int j = 0; j < contentarray.Size; j++) { //Get the raw byte stream stream = (PRStream)contentarray.GetAsStream(j); //Convert to a string. NOTE, you might need a different encoding here content = System.Text.Encoding.ASCII.GetString(PdfReader.GetStreamBytes(stream)); //Look for the OCG token in the stream as well as our watermarked text if (content.IndexOf("/OC") >= 0 && content.IndexOf(watermarkText) >= 0) { //Remove it by giving it zero length and zero data stream.Put(PdfName.LENGTH, new PdfNumber(0)); stream.SetData(new byte[0]); } } } } //Write the content out using (FileStream fs = new FileStream(unwatermarkedFile, FileMode.Create, FileAccess.Write, FileShare.None)) { using (PdfStamper stamper = new PdfStamper(reader2, fs)) { } } this.Close(); }
public void Verify_OptionalContentActionExample_CanBeCreated() { var pdfFilePath = TestUtils.GetOutputFileName(); var stream = new FileStream(pdfFilePath, FileMode.Create); // step 1 var document = new Document(); // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); writer.PdfVersion = PdfWriter.VERSION_1_5; // step 3 document.AddAuthor(TestUtils.Author); document.Open(); // step 4 PdfLayer a1 = new PdfLayer("answer 1", writer); PdfLayer a2 = new PdfLayer("answer 2", writer); PdfLayer a3 = new PdfLayer("answer 3", writer); a1.On = false; a2.On = false; a3.On = false; BaseFont bf = BaseFont.CreateFont(); PdfContentByte cb = writer.DirectContent; cb.BeginText(); cb.SetFontAndSize(bf, 18); cb.ShowTextAligned(Element.ALIGN_LEFT, "Q1: Who is the director of the movie 'Paths of Glory'?", 50, 766, 0); cb.ShowTextAligned(Element.ALIGN_LEFT, "Q2: Who directed the movie 'Lawrence of Arabia'?", 50, 718, 0); cb.ShowTextAligned(Element.ALIGN_LEFT, "Q3: Who is the director of 'House of Flying Daggers'?", 50, 670, 0); cb.EndText(); cb.SaveState(); cb.SetRgbColorFill(0xFF, 0x00, 0x00); cb.BeginText(); cb.BeginLayer(a1); cb.ShowTextAligned(Element.ALIGN_LEFT, "A1: Stanley Kubrick", 50, 742, 0); cb.EndLayer(); cb.BeginLayer(a2); cb.ShowTextAligned(Element.ALIGN_LEFT, "A2: David Lean", 50, 694, 0); cb.EndLayer(); cb.BeginLayer(a3); cb.ShowTextAligned(Element.ALIGN_LEFT, "A3: Zhang Yimou", 50, 646, 0); cb.EndLayer(); cb.EndText(); cb.RestoreState(); var stateOn = new ArrayList { "ON", a1, a2, a3 }; PdfAction actionOn = PdfAction.SetOcGstate(stateOn, true); var stateOff = new ArrayList { "OFF", a1, a2, a3 }; PdfAction actionOff = PdfAction.SetOcGstate(stateOff, true); var stateToggle = new ArrayList { "Toggle", a1, a2, a3 }; PdfAction actionToggle = PdfAction.SetOcGstate(stateToggle, true); Phrase p = new Phrase("Change the state of the answers:"); Chunk on = new Chunk(" on ").SetAction(actionOn); p.Add(on); Chunk off = new Chunk("/ off ").SetAction(actionOff); p.Add(off); Chunk toggle = new Chunk("/ toggle").SetAction(actionToggle); p.Add(toggle); document.Add(p); document.Close(); stream.Dispose(); TestUtils.VerifyPdfFileIsReadable(pdfFilePath); }
public override Arx_File On_Dm_Profile_GetDocument(BaseRegisteredClient client, Dm_Profile dmProfile, Arx_File file, ARXCancelEventArgs e) { // Faccio la trasformazione del documento in uscita per i PDF // Audit dell'evento di modifica di un documento string logFilePath = GetAuditFilePath(); File.AppendAllText(logFilePath, string.Format("{0} GetDocument: {1} [{2} Bytes] Docnumber: {3}/{4} user: {5} SoftwareType: {6} ({7}){8}" , DateTime.Now.ToString("O") , file.FileName , file.FileLength , dmProfile.DOCNUMBER , dmProfile.REVISIONE , client.Utente.ToString() , client.SoftwareType , client.SoftwareName , Environment.NewLine)); // Trasformazione dei documenti PDF per le bolle DOCUMENTTYPE = 2 if (dmProfile.DOCUMENTTYPE == 2) { if (file != null && file.FileName.EndsWith(".pdf", StringComparison.CurrentCultureIgnoreCase)) { string originalFile = file.CurrentFile; string outputWatermarkFileName = Path.GetFileName(file.FileName); string outputWatermarkFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString().Substring(9) + outputWatermarkFileName); // Voglio creare un barcode con il valore del campo numero del profilo string codeText = dmProfile.NUMERO ?? string.Empty; PdfReader originalFileReader = new PdfReader(originalFile); using (FileStream fs = new FileStream(outputWatermarkFilePath, FileMode.Create, FileAccess.Write, FileShare.None)) using (PdfStamper stamper = new PdfStamper(originalFileReader, fs)) { // https://www.codeproject.com/Questions/865666/Adding-comment-on-pdf-layer-created-using-iTextsha int pageCount = originalFileReader.NumberOfPages; // Create New Layer for Watermark PdfLayer layer = new PdfLayer("WatermarkLayer", stamper.Writer); // Loop through each Page for (int i = pageCount; i <= pageCount; i++) { // Getting the Page Size Rectangle rect = originalFileReader.GetPageSize(i); var posY = rect.Height - 50; var posX = 50; // Get the ContentByte object PdfContentByte cb = stamper.GetUnderContent(i); // Tell the cb that the next commands should be "bound" to this new layer cb.BeginLayer(layer); cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 55); PdfGState gState = new PdfGState(); cb.SetGState(gState); string codbartest = codeText; BarcodePDF417 bcpdf417 = new BarcodePDF417(); //Asigna el código de barras en base64 a la propiedad text del objeto.. bcpdf417.Text = ASCIIEncoding.ASCII.GetBytes(codbartest); Image imgpdf417 = bcpdf417.GetImage(); imgpdf417.SetAbsolutePosition(posX, posY); imgpdf417.ScalePercent(200); cb.AddImage(imgpdf417); // Close the layer cb.EndLayer(); } var pdfArxFile = new Arx_File(outputWatermarkFilePath) { FileName = outputWatermarkFileName }; // Restituisco il file elaborato return(pdfArxFile); } } } return(file); }
// =========================================================================== public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); writer.PdfVersion = PdfWriter.VERSION_1_5; // step 3 document.Open(); // step 4 PdfContentByte cb = writer.DirectContent; PdfLayer nested = new PdfLayer("Nested layers", writer); PdfLayer nested_1 = new PdfLayer("Nested layer 1", writer); PdfLayer nested_2 = new PdfLayer("Nested layer 2", writer); nested.AddChild(nested_1); nested.AddChild(nested_2); writer.LockLayer(nested_2); cb.BeginLayer(nested); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("nested layers"), 50, 775, 0 ); cb.EndLayer(); cb.BeginLayer(nested_1); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("nested layer 1"), 100, 800, 0 ); cb.EndLayer(); cb.BeginLayer(nested_2); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("nested layer 2"), 100, 750, 0 ); cb.EndLayer(); PdfLayer group = PdfLayer.CreateTitle("Grouped layers", writer); PdfLayer layer1 = new PdfLayer("Group: layer 1", writer); PdfLayer layer2 = new PdfLayer("Group: layer 2", writer); group.AddChild(layer1); group.AddChild(layer2); cb.BeginLayer(layer1); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("layer 1 in the group"), 50, 700, 0 ); cb.EndLayer(); cb.BeginLayer(layer2); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("layer 2 in the group"), 50, 675, 0 ); cb.EndLayer(); PdfLayer radiogroup = PdfLayer.CreateTitle("Radio group", writer); PdfLayer radio1 = new PdfLayer("Radiogroup: layer 1", writer); radio1.On = true; PdfLayer radio2 = new PdfLayer("Radiogroup: layer 2", writer); radio2.On = false; PdfLayer radio3 = new PdfLayer("Radiogroup: layer 3", writer); radio3.On = false; radiogroup.AddChild(radio1); radiogroup.AddChild(radio2); radiogroup.AddChild(radio3); List <PdfLayer> options = new List <PdfLayer>(); options.Add(radio1); options.Add(radio2); options.Add(radio3); writer.AddOCGRadioGroup(options); cb.BeginLayer(radio1); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("option 1"), 50, 600, 0 ); cb.EndLayer(); cb.BeginLayer(radio2); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase("option 2"), 50, 575, 0 ); cb.EndLayer(); cb.BeginLayer(radio3); ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT, new Phrase( "option 3" ), 50, 550, 0 ); cb.EndLayer(); PdfLayer not_printed = new PdfLayer("not printed", writer); not_printed.OnPanel = false; not_printed.SetPrint("Print", false); cb.BeginLayer(not_printed); ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, new Phrase( "PRINT THIS PAGE" ), 300, 700, 90 ); cb.EndLayer(); PdfLayer zoom = new PdfLayer("Zoom 0.75-1.25", writer); zoom.OnPanel = false; zoom.SetZoom(0.75f, 1.25f); cb.BeginLayer(zoom); ColumnText.ShowTextAligned( cb, Element.ALIGN_LEFT, new Phrase( "Only visible if the zoomfactor is between 75 and 125%" ), 30, 530, 90 ); cb.EndLayer(); } }
private void GeneracionDePDF_Nuevo(List <CajaIndigo.AppPersistencia.Class.ReimpresionComprobantes.Estructura.DATOS_VP> ListViasPagosAux, List <CajaIndigo.AppPersistencia.Class.ReimpresionComprobantes.Estructura.DATOS_DOCUMENTOS> DocsAPagarAux, string InOut) { try { string appRootDir = Convert.ToString(System.IO.Path.GetTempPath()); string startFile = appRootDir + "/PDFs/" + "Chapter1_Example5.pdf"; string watermarkedFile = appRootDir + txtIngreso.Text + "-Nuevo.Text.pdf"; string unwatermarkedFile = appRootDir + "/PDFs/" + "Chapter1_Example5_Un-Watermarked.pdf"; string direct = Convert.ToString(System.IO.Path.GetTempPath()); direct = direct + txtIngreso.Text + ".pdf"; // string appRootDir = Convert.ToString(System.IO.Path.GetTempPath()); // //string appRootDir = new DirectoryInfo(Environment.CurrentDirectory).Parent.Parent.FullName; // string startFile = appRootDir + "/PDFs/" + "Chapter1_Example5.pdf"; // string watermarkedFile = appRootDir + txtIngreso.Text + "-Nuevo.Text.pdf"; //string unwatermarkedFile = appRootDir + "/PDFs/" + "Chapter1_Example5_Un-Watermarked.pdf"; // string direct = Convert.ToString(System.IO.Path.GetTempPath()); // direct = direct + "inchcapeLog\\" + txtIngreso.Text + ".pdf"; // direct = direct + "InduLog\\ResumenMensualMovimientos29092014.pdf"; string watermarkText = "No válido como comprobante"; //Document pdfcommande = new Document(PageSize.LETTER); // Creating a Five paged PDF using (FileStream fs = new FileStream(direct, FileMode.Create, FileAccess.Write, FileShare.None)) using (Document pdfcommande = new Document(PageSize.LETTER, 20f, 20f, 100f, 100f)) //using (Document doc = new Document(PageSize.LETTER)) using (PdfWriter writer = PdfWriter.GetInstance(pdfcommande, fs)) { txtDirect.Text = direct; try { pdfcommande.Open(); pdfcommande.NewPage(); PdfPTable table = new PdfPTable(DGPagos.Columns.Count); table.TotalWidth = 580f; table.LockedWidth = true; table.SpacingBefore = 20f; table.SpacingAfter = 30f; // table.WidthPercentage = 100; List <CajaIndigo.AppPersistencia.Class.ReimpresionComprobantes.Estructura.DATOS_DOCUMENTOS> Docs = new List <CajaIndigo.AppPersistencia.Class.ReimpresionComprobantes.Estructura.DATOS_DOCUMENTOS>(); for (int k = 0; k < DGPagos.Items.Count; k++) { if (k == 0) { DGPagos.Items.MoveCurrentToFirst(); } Docs.Add(DGPagos.Items.CurrentItem as CajaIndigo.AppPersistencia.Class.ReimpresionComprobantes.Estructura.DATOS_DOCUMENTOS); DGPagos.Items.MoveCurrentToNext(); } PdfPCell cell = new PdfPCell(new Phrase(Convert.ToString(label12.Content), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 9f, iTextSharp.text.Font.NORMAL))); //PdfPCell cell2 = new PdfPCell(); cell.Colspan = DGPagos.Columns.Count; cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right table.AddCell(cell); //DataGridColumn Colun = new DataGridColumn(); //in DGPagos.Columns foreach (DataGridColumn column in DGPagos.Columns) { table.AddCell(new Phrase(column.Header.ToString(), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 9f, iTextSharp.text.Font.NORMAL))); } table.HeaderRows = 1; string FechaAFormatear; string Dia; string Mes; string Ano; FormatoMonedas FM = new FormatoMonedas(); string MonedaFormateada; for (int k = 0; k < Docs.Count; k++) { if (Docs[k] != null) { PdfPCell cellrow1 = new PdfPCell(new Phrase(Convert.ToString(Docs[k].TXT_DOCU), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 8f, iTextSharp.text.Font.NORMAL))); table.AddCell(cellrow1); PdfPCell cellrow2 = new PdfPCell(new Phrase(Convert.ToString(Docs[k].NRO_DOCUMENTO), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 8f, iTextSharp.text.Font.NORMAL))); table.AddCell(cellrow2); Dia = Docs[k].FECHA_DOC.Substring(8, 2); Mes = Docs[k].FECHA_DOC.Substring(5, 2); Ano = Docs[k].FECHA_DOC.Substring(0, 4); FechaAFormatear = Dia + "/" + Mes + "/" + Ano; PdfPCell cellrow3 = new PdfPCell(new Phrase(String.Format("{0:dd/MM/yyyy}", FechaAFormatear), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 8f, iTextSharp.text.Font.NORMAL))); table.AddCell(cellrow3); Dia = Docs[k].FECHA_VENC_DOC.Substring(8, 2); Mes = Docs[k].FECHA_VENC_DOC.Substring(5, 2); Ano = Docs[k].FECHA_VENC_DOC.Substring(0, 4); FechaAFormatear = Dia + "/" + Mes + "/" + Ano; PdfPCell cellrow4 = new PdfPCell(new Phrase(String.Format("{0:dd/MM/yyyy}", FechaAFormatear), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 8f, iTextSharp.text.Font.NORMAL))); table.AddCell(cellrow4); if (txtMoneda.Text == "CLP") { MonedaFormateada = FM.FormatoMonedaCaja(Docs[k].MONTO_DOC_ML, "Ch", "1"); } else { MonedaFormateada = FM.FormatoMonedaCaja(Docs[k].MONTO_DOC_ML, "Ex", "1"); } PdfPCell cellrow5 = new PdfPCell(new Phrase(MonedaFormateada, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 8f, iTextSharp.text.Font.NORMAL))); table.AddCell(cellrow5); if (txtMoneda.Text == "CLP") { MonedaFormateada = FM.FormatoMonedaCaja(Docs[k].MONTO_DOC_MO, "Ch", "1"); } else { MonedaFormateada = FM.FormatoMonedaCaja(Docs[k].MONTO_DOC_MO, "Ex", "1"); } PdfPCell cellrow6 = new PdfPCell(new Phrase(MonedaFormateada, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 8f, iTextSharp.text.Font.NORMAL))); table.AddCell(cellrow6); } } IEnumerable itemsSource = DGPagos.ItemsSource as IEnumerable; PdfPTable table2 = new PdfPTable(DGResumenViasPago.Columns.Count); table2.TotalWidth = 580f; table2.LockedWidth = true; table2.SpacingBefore = 20f; table2.SpacingAfter = 30f; List <CajaIndigo.AppPersistencia.Class.ReimpresionComprobantes.Estructura.DATOS_VP> ViasPago = new List <CajaIndigo.AppPersistencia.Class.ReimpresionComprobantes.Estructura.DATOS_VP>(); for (int k = 0; k < DGResumenViasPago.Items.Count; k++) { if (k == 0) { DGResumenViasPago.Items.MoveCurrentToFirst(); } ViasPago.Add(DGResumenViasPago.Items.CurrentItem as CajaIndigo.AppPersistencia.Class.ReimpresionComprobantes.Estructura.DATOS_VP); DGResumenViasPago.Items.MoveCurrentToNext(); } PdfPCell cell2 = new PdfPCell(new Phrase(Convert.ToString(label11.Content), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 9f, iTextSharp.text.Font.NORMAL))); //PdfPCell cell2 = new PdfPCell(); cell2.Colspan = DGResumenViasPago.Columns.Count; cell2.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right table2.AddCell(cell2); foreach (DataGridColumn column in DGResumenViasPago.Columns) { table2.AddCell(new Phrase(column.Header.ToString(), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 9f, iTextSharp.text.Font.NORMAL))); } table2.HeaderRows = 1; for (int k = 0; k < ViasPago.Count; k++) { if (ViasPago[k] != null) { PdfPCell cellrow1 = new PdfPCell(new Phrase(Convert.ToString(ViasPago[k].NUM_POS), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 8f, iTextSharp.text.Font.NORMAL))); table2.AddCell(cellrow1); PdfPCell cellrow2 = new PdfPCell(new Phrase(Convert.ToString(ViasPago[k].DESCRIP_VP), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 8f, iTextSharp.text.Font.NORMAL))); table2.AddCell(cellrow2); PdfPCell cellrow3 = new PdfPCell(new Phrase(Convert.ToString(ViasPago[k].NUM_VP), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 8f, iTextSharp.text.Font.NORMAL))); table2.AddCell(cellrow3); Dia = ViasPago[k].FECHA_EMISION.Substring(8, 2); Mes = ViasPago[k].FECHA_EMISION.Substring(5, 2); Ano = ViasPago[k].FECHA_EMISION.Substring(0, 4); FechaAFormatear = Dia + "/" + Mes + "/" + Ano; PdfPCell cellrow4 = new PdfPCell(new Phrase(String.Format("{0:dd/MM/yyyy}", FechaAFormatear), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 8f, iTextSharp.text.Font.NORMAL))); table2.AddCell(cellrow4); Dia = ViasPago[k].FECHA_VENC.Substring(8, 2); Mes = ViasPago[k].FECHA_VENC.Substring(5, 2); Ano = ViasPago[k].FECHA_VENC.Substring(0, 4); FechaAFormatear = Dia + "/" + Mes + "/" + Ano; PdfPCell cellrow5 = new PdfPCell(new Phrase(String.Format("{0:dd/MM/yyyy}", FechaAFormatear), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 8f, iTextSharp.text.Font.NORMAL))); table2.AddCell(cellrow5); if (txtMoneda.Text == "CLP") { MonedaFormateada = FM.FormatoMonedaCaja(ViasPago[k].MONTO_ML, "Ch", "1"); } else { MonedaFormateada = FM.FormatoMonedaCaja(ViasPago[k].MONTO_ML, "Ex", "1"); } PdfPCell cellrow6 = new PdfPCell(new Phrase(MonedaFormateada, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 8f, iTextSharp.text.Font.NORMAL))); table2.AddCell(cellrow6); if (txtMoneda.Text == "CLP") { MonedaFormateada = FM.FormatoMonedaCaja(ViasPago[k].MONTO_MO, "Ch", "1"); } else { MonedaFormateada = FM.FormatoMonedaCaja(ViasPago[k].MONTO_MO, "Ex", "1"); } PdfPCell cellrow7 = new PdfPCell(new Phrase(MonedaFormateada, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 8f, iTextSharp.text.Font.NORMAL))); table2.AddCell(cellrow7); } } pdfcommande.Add(iTextSharp.text.PageSize.LETTER); string texto = ""; //Titulo texto = "Comprobante de " + InOut; iTextSharp.text.Paragraph itxtTitulo = new iTextSharp.text.Paragraph(texto); itxtTitulo.IndentationLeft = 200; itxtTitulo.Font.Size = 14; itxtTitulo.Font.SetStyle("bold"); itxtTitulo.Font.SetFamily("courier"); itxtTitulo.SpacingBefore = 10f; itxtTitulo.SpacingAfter = 10f; pdfcommande.Add(itxtTitulo); //DATOS CAJA texto = Convert.ToString(label6.Content) + txtNomCaja.Text + " " + Convert.ToString(label7.Content) + txtCajero.Text; iTextSharp.text.Paragraph itxtHeader = new iTextSharp.text.Paragraph(texto); itxtHeader.IndentationLeft = 10; itxtHeader.Font.Size = 9; itxtHeader.Font.SetFamily("courier"); itxtHeader.Alignment = Element.ALIGN_LEFT; pdfcommande.Add(itxtHeader); texto = " "; pdfcommande.Add(new iTextSharp.text.Paragraph(texto)); //DATOS CLIENTE //TABLE F PdfPTable tablef = new PdfPTable(4); tablef.TotalWidth = 580f; tablef.LockedWidth = true; //tablef.HorizontalAlignment = 0; tablef.SpacingBefore = 15f; tablef.SpacingAfter = 20f; //float[] widths = new float[] { 40f, 40f, 50f, 120f}; float[] widths = new float[] { 145f, 145f, 100f, 190f }; tablef.SetWidths(widths); //cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right PdfPCell cellrow1f = new PdfPCell(new Phrase("RUT Cliente:", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 9f, iTextSharp.text.Font.NORMAL))); //cellrow1f.Border = 8; cellrow1f.Left = 0; cellrow1f.HorizontalAlignment = 0; tablef.AddCell(cellrow1f); //, iTextSharp.text.Font.NORMAL,iTextSharp.text.BaseColor.WHITE PdfPCell cellrow2f = new PdfPCell(new Phrase(txtRUT.Text, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 9f, iTextSharp.text.Font.NORMAL))); //cellrow2f.Border = 8; cellrow2f.HorizontalAlignment = 0; cellrow2f.Left = 200f; tablef.AddCell(cellrow2f); PdfPCell cellrow3f = new PdfPCell(new Phrase("Nombre cliente:", new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 9f, iTextSharp.text.Font.NORMAL))); //cellrow3f.Border = 8; cellrow3f.Left = 160f; cellrow3f.HorizontalAlignment = 0; tablef.AddCell(cellrow3f); PdfPCell cellrow4f = new PdfPCell(new Phrase(txtNomCli.Text, new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.COURIER, 9f, iTextSharp.text.Font.NORMAL))); //cellrow4f.Border = 8; cellrow4f.HorizontalAlignment = 0; tablef.AddCell(cellrow4f); pdfcommande.Add(tablef); pdfcommande.Add(table); pdfcommande.Add(table2); } catch (Exception ex) { Console.Write(ex.Message, ex.StackTrace); } pdfcommande.Close(); pdfcommande.Dispose(); } try { // Creating watermark on a separate layer // Creating iTextSharp.text.pdf.PdfReader object to read the Existing PDF Document produced by 1 no. string direct2 = Convert.ToString(System.IO.Path.GetTempPath()); direct2 = direct2 + "inchcapeLog\\ResumenMensualMovimientos29092014.pdf"; PdfReader reader1 = new PdfReader(direct); using (FileStream fs = new FileStream(watermarkedFile, FileMode.Create, FileAccess.Write, FileShare.None)) // Creating iTextSharp.text.pdf.PdfStamper object to write Data from iTextSharp.text.pdf.PdfReader object to FileStream object using (PdfStamper stamper = new PdfStamper(reader1, fs)) { // Getting total number of pages of the Existing Document int pageCount = reader1.NumberOfPages; // Create New Layer for Watermark PdfLayer layer = new PdfLayer("WatermarkLayer", stamper.Writer); //PdfLayer layer2 = new PdfLayer("Paginacion",tablex); // Loop through each Page for (int i = 1; i <= pageCount; i++) { string PaginaActual = Convert.ToString(i); string PaginasTotales = Convert.ToString(pageCount); // Getting the Page Size iTextSharp.text.Rectangle rect = reader1.GetPageSize(i); if ((txtMandante.Text == "100") | (txtMandante.Text == "200")) { // Get the ContentByte object PdfContentByte cb = stamper.GetUnderContent(i); // Tell the cb that the next commands should be "bound" to this new layer cb.BeginLayer(layer); cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 50); PdfGState gState = new PdfGState(); gState.FillOpacity = 0.25f; cb.SetGState(gState); cb.SetColorFill(BaseColor.BLACK); cb.BeginText(); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, watermarkText, rect.Width / 2, rect.Height / 2, 45f); cb.EndText(); // Close the layer cb.EndLayer(); } //PAGINACION PdfContentByte cb2 = stamper.GetUnderContent(i); cb2.BeginLayer(layer); cb2.SetFontAndSize(BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9); PdfGState gState2 = new PdfGState(); gState2.FillOpacity = 1f; cb2.SetGState(gState2); cb2.SetColorFill(BaseColor.BLACK); cb2.BeginText(); string Paginas = "Pagina: " + PaginaActual + " De: " + PaginasTotales; cb2.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, Paginas, rect.Width - 13, rect.Height - 20, 0f); cb2.EndText(); // Close the layer cb2.EndLayer(); //FECHA LABEL PdfContentByte cb4a = stamper.GetUnderContent(i); cb4a.BeginLayer(layer); cb4a.SetFontAndSize(BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9); gState2.FillOpacity = 1f; cb4a.SetGState(gState2); cb4a.SetColorFill(BaseColor.BLACK); cb4a.BeginText(); cb4a.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Fecha:", rect.Width - 70, rect.Height - 30, 0f); cb4a.EndText(); // Close the layer cb4a.EndLayer(); //FECHA PdfContentByte cb4 = stamper.GetUnderContent(i); cb4.BeginLayer(layer); cb4.SetFontAndSize(BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9); gState2.FillOpacity = 1f; cb4.SetGState(gState2); cb4.SetColorFill(BaseColor.BLACK); cb4.BeginText(); string FechaAFormatear = Convert.ToString(DateTime.Now).Substring(0, 10); cb4.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, String.Format("{0:dd/MM/yyyy}", FechaAFormatear), rect.Width - 13, rect.Height - 30, 0f); cb4.EndText(); // Close the layer cb4.EndLayer(); //HORA PdfContentByte cb6 = stamper.GetUnderContent(i); cb6.BeginLayer(layer); cb6.SetFontAndSize(BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9); gState2.FillOpacity = 1f; cb6.SetGState(gState2); cb6.SetColorFill(BaseColor.BLACK); cb6.BeginText(); FechaAFormatear = Convert.ToString(DateTime.Now.Hour + ":" + Convert.ToString(DateTime.Now.Minute) + ":" + Convert.ToString(DateTime.Now.Second)); cb6.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, String.Format("{0:HH:mm:ss}", FechaAFormatear), rect.Width - 13, rect.Height - 40, 0f); cb6.EndText(); // Close the layer cb6.EndLayer(); //HORA LABEL PdfContentByte cb6a = stamper.GetUnderContent(i); cb6a.BeginLayer(layer); cb6a.SetFontAndSize(BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9); gState2.FillOpacity = 1f; cb6a.SetGState(gState2); cb6a.SetColorFill(BaseColor.BLACK); cb6a.BeginText(); cb6a.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Hora:", rect.Width - 70, rect.Height - 40, 0f); cb6a.EndText(); // Close the layer cb6a.EndLayer(); //USUARIO PdfContentByte cb8 = stamper.GetUnderContent(i); cb8.BeginLayer(layer); cb8.SetFontAndSize(BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9); gState2.FillOpacity = 1f; cb8.SetGState(gState2); cb8.SetColorFill(BaseColor.BLACK); cb8.BeginText(); FechaAFormatear = Convert.ToString(DateTime.Now.Hour + ":" + Convert.ToString(DateTime.Now.Minute) + ":" + Convert.ToString(DateTime.Now.Second)); cb8.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, txtUsuario.Text, rect.Width - 13, rect.Height - 50, 0f); cb8.EndText(); // Close the layer cb8.EndLayer(); //USUARIO LABEL PdfContentByte cb8a = stamper.GetUnderContent(i); cb8a.BeginLayer(layer); cb8a.SetFontAndSize(BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9); gState2.FillOpacity = 1f; cb8a.SetGState(gState2); cb8a.SetColorFill(BaseColor.BLACK); cb8a.BeginText(); cb8a.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Usuario:", rect.Width - 70, rect.Height - 50, 0f); cb8a.EndText(); // Close the layer cb8a.EndLayer(); //INGRESO PdfContentByte cb9 = stamper.GetUnderContent(i); cb9.BeginLayer(layer); cb9.SetFontAndSize(BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9); gState2.FillOpacity = 1f; cb9.SetGState(gState2); cb9.SetColorFill(BaseColor.BLACK); cb9.BeginText(); FechaAFormatear = Convert.ToString(DateTime.Now.Hour + ":" + Convert.ToString(DateTime.Now.Minute) + ":" + Convert.ToString(DateTime.Now.Second)); cb9.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, txtIngreso.Text, rect.Width - 13, rect.Height - 60, 0f); cb9.EndText(); // Close the layer cb9.EndLayer(); //INGRESO LABEL PdfContentByte cb9a = stamper.GetUnderContent(i); cb9a.BeginLayer(layer); cb9a.SetFontAndSize(BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9); gState2.FillOpacity = 1f; cb9a.SetGState(gState2); cb9a.SetColorFill(BaseColor.BLACK); cb9a.BeginText(); cb9a.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Ingreso:", rect.Width - 70, rect.Height - 60, 0f); cb9a.EndText(); // Close the layer cb9a.EndLayer(); //NTA VENTA PdfContentByte cb10 = stamper.GetUnderContent(i); cb10.BeginLayer(layer); cb10.SetFontAndSize(BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9); gState2.FillOpacity = 1f; cb10.SetGState(gState2); cb10.SetColorFill(BaseColor.BLACK); cb10.BeginText(); FechaAFormatear = Convert.ToString(DateTime.Now.Hour + ":" + Convert.ToString(DateTime.Now.Minute) + ":" + Convert.ToString(DateTime.Now.Second)); cb10.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, txtNotaVta.Text, rect.Width - 13, rect.Height - 70, 0f); cb10.EndText(); // Close the layer cb10.EndLayer(); //NTA VENTA LABEL PdfContentByte cb10a = stamper.GetUnderContent(i); cb10a.BeginLayer(layer); cb10a.SetFontAndSize(BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9); gState2.FillOpacity = 1f; cb10a.SetGState(gState2); cb10a.SetColorFill(BaseColor.BLACK); cb10a.BeginText(); cb10a.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Nota de venta:", rect.Width - 70, rect.Height - 70, 0f); cb10a.EndText(); // Close the layer cb10a.EndLayer(); //DOC CONTABLE PdfContentByte cb11 = stamper.GetUnderContent(i); cb11.BeginLayer(layer); cb11.SetFontAndSize(BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9); gState2.FillOpacity = 1f; cb11.SetGState(gState2); cb11.SetColorFill(BaseColor.BLACK); cb11.BeginText(); FechaAFormatear = Convert.ToString(DateTime.Now.Hour + ":" + Convert.ToString(DateTime.Now.Minute) + ":" + Convert.ToString(DateTime.Now.Second)); cb11.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, txtNumDocCont.Text, rect.Width - 13, rect.Height - 80, 0f); cb11.EndText(); // Close the layer cb11.EndLayer(); //DOC CONTABLE LABEL PdfContentByte cb11a = stamper.GetUnderContent(i); cb11a.BeginLayer(layer); cb11a.SetFontAndSize(BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9); gState2.FillOpacity = 1f; cb11a.SetGState(gState2); cb11a.SetColorFill(BaseColor.BLACK); cb11a.BeginText(); cb11a.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Doc. Contable:", rect.Width - 70, rect.Height - 80, 0f); cb11a.EndText(); // Close the layer cb11a.EndLayer(); //PEDIDO PdfContentByte cb12 = stamper.GetUnderContent(i); cb12.BeginLayer(layer); cb12.SetFontAndSize(BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9); gState2.FillOpacity = 1f; cb12.SetGState(gState2); cb12.SetColorFill(BaseColor.BLACK); cb12.BeginText(); FechaAFormatear = Convert.ToString(DateTime.Now.Hour + ":" + Convert.ToString(DateTime.Now.Minute) + ":" + Convert.ToString(DateTime.Now.Second)); cb12.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, txtPedido.Text, rect.Width - 13, rect.Height - 90, 0f); cb12.EndText(); // Close the layer cb12.EndLayer(); //PEDIDO LABEL PdfContentByte cb12a = stamper.GetUnderContent(i); cb12a.BeginLayer(layer); cb12a.SetFontAndSize(BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9); gState2.FillOpacity = 1f; cb12a.SetGState(gState2); cb12a.SetColorFill(BaseColor.BLACK); cb12a.BeginText(); cb12a.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "N° Pedido:", rect.Width - 78, rect.Height - 90, 0f); cb12a.EndText(); // Close the layer cb12a.EndLayer(); //if (txtSociedad.Text == "EI17") //{ // if (i == 1) // { // PdfContentByte cb14a = stamper.GetUnderContent(i); // iTextSharp.text.Image Soc17 = iTextSharp.text.Image.GetInstance(CajaIndigo.Properties.Resources.camiones, System.Drawing.Imaging.ImageFormat.Jpeg); // Soc17.Alignment = iTextSharp.text.Image.ALIGN_LEFT; // cb14a.BeginLayer(layer); // cb14a.SetFontAndSize(BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9); // gState2.FillOpacity = 1f; // cb14a.SetGState(gState2); // cb14a.SetColorFill(BaseColor.BLACK); // cb14a.BeginText(); // Soc17.SetAbsolutePosition(20, 700); // Soc17.ScaleAbsolute(200, 40); // cb14a.AddImage(Soc17); // cb14a.EndText(); // cb14a.EndLayer(); // PdfContentByte cb13a = stamper.GetUnderContent(i); // iTextSharp.text.Image logos = iTextSharp.text.Image.GetInstance(CajaIndigo.Properties.Resources.HUINCHA_CYB, System.Drawing.Imaging.ImageFormat.Jpeg); // logos.Alignment = iTextSharp.text.Image.ALIGN_CENTER; // logos.SetAbsolutePosition(15, rect.Height - (rect.Height - 65)); // logos.ScaleAbsolute(580,75); // cb13a.BeginLayer(layer); // cb13a.SetFontAndSize(BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9); // gState2.FillOpacity = 1f; // cb13a.SetGState(gState2); // cb13a.SetColorFill(BaseColor.BLACK); // cb13a.BeginText(); // cb13a.AddImage(logos); // cb13a.EndText(); // // Close the layer // cb13a.EndLayer(); // } //} if (txtSociedad.Text == "EI33") { if (i == 1) { PdfContentByte cb14 = stamper.GetUnderContent(i); //DirectImages = System.IO.Directory.GetCurrentDirectory(); iTextSharp.text.Image Soc15 = iTextSharp.text.Image.GetInstance(CajaIndigo.Properties.Resources.retail, System.Drawing.Imaging.ImageFormat.Png); Soc15.Alignment = iTextSharp.text.Image.ALIGN_LEFT; Soc15.SetAbsolutePosition(20, 700); Soc15.ScaleAbsolute(150, 50); cb14.BeginLayer(layer); cb14.SetFontAndSize(BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9); gState2.FillOpacity = 1f; cb14.SetGState(gState2); cb14.SetColorFill(BaseColor.BLACK); cb14.BeginText(); cb14.AddImage(Soc15); cb14.EndText(); // Close the layer cb14.EndLayer(); // PdfContentByte cb13a = stamper.GetUnderContent(i); // iTextSharp.text.Image logos = iTextSharp.text.Image.GetInstance(CajaIndigo.Properties.Resources.LOGOSONE__1__01, System.Drawing.Imaging.ImageFormat.Png); // logos.Alignment = iTextSharp.text.Image.ALIGN_CENTER; // logos.SetAbsolutePosition(15, rect.Height - (rect.Height - 65)); // logos.ScaleAbsolute(580, 70); // cb13a.BeginLayer(layer); // cb13a.SetFontAndSize(BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9); // gState2.FillOpacity = 1f; // cb13a.SetGState(gState2); // cb13a.SetColorFill(BaseColor.BLACK); // cb13a.BeginText(); // cb13a.AddImage(logos); // cb13a.EndText(); //// Close the layer // cb13a.EndLayer(); } } } } } catch (Exception ex) { Console.Write(ex.Message, ex.StackTrace); System.Windows.MessageBox.Show(ex.Message + ex.StackTrace); } string url_reimpresion = ""; url_reimpresion = watermarkedFile; System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = url_reimpresion; proc.Start(); proc.Close(); this.Visibility = Visibility.Collapsed; GC.Collect(); //string url_reimpresion = ""; //url_reimpresion = watermarkedFile; //PDFViewer pdfvisor = new PDFViewer(); //pdfvisor.webBrowser1.Navigate(url_reimpresion); //pdfvisor.txtArchivo.Text = watermarkedFile; //pdfvisor.txtArchivoNuevo.Text = direct; //pdfvisor.Owner = this; //pdfvisor.Show(); //this.Visibility = Visibility.Collapsed; //GC.Collect(); } catch (Exception ex) { System.Windows.MessageBox.Show(ex.Message + ex.StackTrace); Console.Write(ex.Message, ex.StackTrace); } }
public Example5() { string appRootDir = new DirectoryInfo(Environment.CurrentDirectory).Parent.Parent.FullName; string startFile = appRootDir + "/PDFs/" + "Chapter1_Example5.pdf"; string watermarkedFile = appRootDir + "/PDFs/" + "Chapter1_Example5_Watermarked.pdf"; string unwatermarkedFile = appRootDir + "/PDFs/" + "Chapter1_Example5_Un-Watermarked.pdf"; string watermarkText = "This is a Test"; // Creating a Five paged PDF using (FileStream fs = new FileStream(startFile, FileMode.Create, FileAccess.Write, FileShare.None)) using (Document doc = new Document(PageSize.LETTER)) using (PdfWriter writer = PdfWriter.GetInstance(doc, fs)) { doc.Open(); for (int i = 1; i <= 5; i++) { doc.NewPage(); doc.Add(new Paragraph(string.Format("This is a page {0}", i))); } doc.Close(); } // Creating watermark on a separate layer // Creating iTextSharp.text.pdf.PdfReader object to read the Existing PDF Document produced by 1 no. PdfReader reader1 = new PdfReader(startFile); using (FileStream fs = new FileStream(watermarkedFile, FileMode.Create, FileAccess.Write, FileShare.None)) // Creating iTextSharp.text.pdf.PdfStamper object to write Data from iTextSharp.text.pdf.PdfReader object to FileStream object using (PdfStamper stamper = new PdfStamper(reader1, fs)) { // Getting total number of pages of the Existing Document int pageCount = reader1.NumberOfPages; // Create New Layer for Watermark PdfLayer layer = new PdfLayer("WatermarkLayer", stamper.Writer); // Loop through each Page for (int i = 1; i <= pageCount; i++) { // Getting the Page Size Rectangle rect = reader1.GetPageSize(i); // Get the ContentByte object PdfContentByte cb = stamper.GetUnderContent(i); // Tell the cb that the next commands should be "bound" to this new layer cb.BeginLayer(layer); cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 50); PdfGState gState = new PdfGState(); gState.FillOpacity = 0.25f; cb.SetGState(gState); cb.SetColorFill(BaseColor.BLACK); cb.BeginText(); cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, watermarkText, rect.Width / 2, rect.Height / 2, 45f); cb.EndText(); // Close the layer cb.EndLayer(); } } // Removing the layer created above // 1. First we bind a reader to the watermarked file // 2. Then strip out a branch of things // 3. Finally use a simple stamper to write out the edited reader PdfReader reader2 = new PdfReader(watermarkedFile); // NOTE: This will destroy all layers in the Document, only use if you don't have any addtional layers // Remove the OCG group completely from the Document: reader2.Catalog.Remove(PdfName.OCPROPERTIES); // Clean up the reader, optional reader2.RemoveUnusedObjects(); // Placeholder variables PRStream stream; string content; PdfDictionary page; PdfArray contentArray; // Get the number of pages int pageCount2 = reader2.NumberOfPages; // Loop through each page for (int i = 1; i <= pageCount2; i++) { // Get the page page = reader2.GetPageN(i); // Get the raw content contentArray = page.GetAsArray(PdfName.CONTENTS); if (contentArray != null) { // Loop through content for (int j = 0; j < contentArray.Size; j++) { stream = (PRStream)contentArray.GetAsStream(j); // Convert to a String, NOTE: you might need a different encoding here content = System.Text.Encoding.ASCII.GetString(PdfReader.GetStreamBytes(stream)); //Look for the OCG token in the stream as well as our watermarked text if (content.IndexOf("/OC") >= 0 && content.IndexOf(watermarkText) >= 0) { //Remove it by giving it zero length and zero data stream.Put(PdfName.LENGTH, new PdfNumber(0)); stream.SetData(new byte[0]); } } } } // Write the content out using (FileStream fs = new FileStream(unwatermarkedFile, FileMode.Create, FileAccess.Write, FileShare.None)) using (PdfStamper stamper = new PdfStamper(reader2, fs)) { } }