public static void addValidateFunction(PdfWriter writer) { writer.AddJavaScript("var reqFields; "); string validateFunction = "function validate () { app.alert('This will validate the required fields'); " + " for (i=0; i<reqFields.length; i++) { " + " var grp = this.getField(reqFields[i]); app.alert(grp.value); " + " if (!grp || grp.value === null || grp.value == ''|| grp.value=='Off') { " + " app.alert('please select this '+ reqFields[i]); return false; }}" + "return true}"; writer.AddJavaScript(validateFunction); }
public static void AddPrintFunction(string pdfPath, Stream outputStream) { PdfReader reader = new PdfReader(pdfPath); int pageCount = reader.NumberOfPages; Rectangle pageSize = reader.GetPageSize(1); // Set up Writer PdfDocument document = new PdfDocument(); PdfWriter writer = PdfWriter.GetInstance(document, outputStream); document.Open(); //Copy each page PdfContentByte content = writer.DirectContent; for (int i = 0; i < pageCount; i++) { document.NewPage(); // page numbers are one based PdfImportedPage page = writer.GetImportedPage(reader, i + 1); // x and y correspond to position on the page content.AddTemplate(page, 0, 0); } // Inert Javascript to print the document after a fraction of a second to allow time to become visible. string jsText = "var res = app.setTimeOut(‘var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);’, 200);"; //string jsTextNoWait = “var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);”; PdfAction js = PdfAction.JavaScript(jsText, writer); writer.AddJavaScript(js); document.Close(); }
public Chap1106() { Console.WriteLine("Chapter 11 example 6: javascript"); // step 1: creation of a document-object Document document = new Document(PageSize.A4, 50, 50, 50, 50); try { // step 2: // we create a writer that listens to the document // and directs a PDF-stream to a file PdfWriter writer = PdfWriter.GetInstance(document, new FileStream("Chap1106.pdf", FileMode.Create)); // step 3: we open the document document.Open(); // step 4: we add content PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer); writer.AddJavaScript(jAction); document.Add(new Paragraph("Page 1")); } catch (Exception de) { Console.Error.WriteLine(de.Message); Console.Error.WriteLine(de.StackTrace); } // step 5: we close the document document.Close(); }
/* will print A4 Landscape 11.69 x 8.27 */ protected void print_A4_landscape() { Warning[] warnings; string[] streamids; string mimeType; string encoding; string extension; string dtnow = DateTime.Now.ToString("ddMMMyyyy_hh_mm_ss"); byte[] bytes = ReportViewer1.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings); string fileOUT = HttpContext.Current.Server.MapPath(@"\Areas\ManagementReports\Reports\TempReport\" + "output_" + dtnow + "_" + rtype.ToString() + ".pdf"); FileStream fs = new FileStream(fileOUT, FileMode.Create); fs.Write(bytes, 0, bytes.Length); fs.Close(); Document document = new Document(PageSize.A4.Rotate()); //Open existing PDF PdfReader reader = new PdfReader(fileOUT); //Getting a instance of new PDF writer PdfWriter writer = PdfWriter.GetInstance(document, new FileStream( HttpContext.Current.Server.MapPath(@"\Areas\ManagementReports\Reports\TempReport\" + "print_" + dtnow + "_" + rtype.ToString() + ".pdf"), FileMode.Create)); document.Open(); PdfContentByte cb = writer.DirectContent; int i = 0; int p = 0; int n = reader.NumberOfPages; Rectangle psize = reader.GetPageSize(1); float width = psize.Width; float height = psize.Height; //Add Page to new document while (i < n) { document.NewPage(); p++; i++; PdfImportedPage page1 = writer.GetImportedPage(reader, i); cb.AddTemplate(page1, 0, 0); } //Attach javascript to the document PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer); writer.AddJavaScript(jAction); document.Close(); //Attach pdf to the iframe //frmPrint.Attributes["src"] = @"\Areas\ManagementReports\Reports\TempReport\" + "print_" + dtnow + "_" + rtype.ToString() + ".pdf"; }
public FileResult Export(string GridHtml) { try { using (MemoryStream stream = new System.IO.MemoryStream()) { StringReader sr = new StringReader(GridHtml); Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f); PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream); pdfDoc.Open(); XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr); //js var jsBuilder = JSContentinString("http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"); jsBuilder += JSContentinString("https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-AMS_HTML-full"); // var webRequest = WebRequest.Create(@"https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-AMS_HTML-full"); //using (var response = webRequest.GetResponse()) //using (var content = response.GetResponseStream()) //using (var reader = new StreamReader(content)) //{ // // // var scriptcontent = "<script type = \"text/x-mathjax-config\" >MathJax.Hub.Config({tex2jax: { inlineMath: [[\"$\", \"$\"],[\"\\(\",\"\\)\"]]}});</script>"; // var strContent = reader.ReadToEnd(); // var body = "<p>When $a \ne 0$, there are two solutions to \\(ax ^ 2 + bx + c = 0\\) and they are $$x = { -b \\pm \\sqrt{ b ^ 2 - 4ac} \\over 2a}.$$</p> "; //Phrase phrase1 = new Phrase("Hello world. Checking Print Functionality"); //pdfDoc.Add(phrase1); //Phrase phrase2 = new Phrase(body); //pdfDoc.Add(phrase2); // writer.AddJavaScript(scriptcontent + strContent + body + "this.print();"); //writer.AddJavaScript("this.print();"); // string jsText = "var res = app.setTimeOut('var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);', 200);"; // writer.AddJavaScript(webRequest); // // } pdfDoc.NewPage(); // var webRequest = WebRequest.Create(@"https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-AMS_HTML-full"); // string script = "MathJax.Hub.Config({tex2jax: { inlineMath: [[\"$\", \"$\"],[\"\\\\(\",\"\\\\)\"]]}});"; writer.AddJavaScript("this.print();"); pdfDoc.Close(); return(File(stream.ToArray(), "application/pdf", "Grid.pdf")); } } catch (Exception ex) { throw; } }
protected void btnPrint_Click(object sender, EventArgs e) { Warning[] warnings; string[] streamids; string mimeType; string encoding; string extension; byte[] bytes = ReportViewer1.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings); FileStream fs = new FileStream(HttpContext.Current.Server.MapPath("output.pdf"), FileMode.Create); fs.Write(bytes, 0, bytes.Length); fs.Close(); //Open existing PDF Document document = new Document(PageSize.LETTER); PdfReader reader = new PdfReader(HttpContext.Current.Server.MapPath("output.pdf")); //Getting a instance of new PDF writer PdfWriter writer = PdfWriter.GetInstance(document, new FileStream( HttpContext.Current.Server.MapPath("Print.pdf"), FileMode.Create)); document.Open(); PdfContentByte cb = writer.DirectContent; int i = 0; int p = 0; int n = reader.NumberOfPages; Rectangle psize = reader.GetPageSize(1); float width = psize.Width; float height = psize.Height; //Add Page to new document while (i < n) { document.NewPage(); p++; i++; PdfImportedPage page1 = writer.GetImportedPage(reader, i); cb.AddTemplate(page1, 0, 0); } //Attach javascript to the document PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer); writer.AddJavaScript(jAction); document.Close(); //Attach pdf to the iframe frmPrint.Attributes["src"] = "Print.pdf"; }
private void addAutoPrint() { if (PageSetup.PrintingPreferences == null) { return; } if (PageSetup.PrintingPreferences.ShowPrintDialogAutomatically) { PdfWriter.AddJavaScript("this.print(true);"); } }
private void SetPDFViewerPropertiesPost(PdfWriter writer) { if (EnablePDFAutomaticPrint) { string jsText = String.Empty; if (PDFAutomaticPrintWaitTime > 0) { jsText = "var res = app.setTimeOut('var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);', " + PDFAutomaticPrintWaitTime + ");"; } else { jsText = "var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);"; } PdfAction js = PdfAction.JavaScript(jsText, writer); writer.AddJavaScript(js); } }
public static void addRequiredFields(PdfWriter writer, List <String> fieldNames) { String fieldString = ""; foreach (string s in fieldNames) { if (fieldString == null || fieldString.Length == 0) { fieldString = fieldString + "'" + s + "'"; } else { fieldString = fieldString + ",'" + s + "'"; } } writer.AddJavaScript("reqFields = [" + fieldString + "];"); Console.WriteLine("reqFields = [" + fieldString + "];"); }
public void pPDF() { //Open existing PDF Document document = new Document(PageSize.LETTER); PdfReader reader = new PdfReader(Server.MapPath("~/Report/nasser7.pdf")); //Getting a instance of new PDF writer PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Server.MapPath("~/Report/nasser12.pdf"), FileMode.Create)); document.Open(); PdfContentByte cb = writer.DirectContent; int i = 0; int p = 0; int n = reader.NumberOfPages; Rectangle psize = reader.GetPageSize(1); float width = psize.Width; float height = psize.Height; //Add Page to new document while (i < n) { document.NewPage(); p += 1; i += 1; PdfImportedPage page1 = writer.GetImportedPage(reader, i); cb.AddTemplate(page1, 0, 0); } //Attach javascript to the document PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer); writer.AddJavaScript(jAction); document.Close(); //Attach pdf to the iframe //frmPrint.Attributes("src") = "Print2.pdf"; }
// --------------------------------------------------------------------------- /** * Creates a PDF document for PdfReader. * @param stream the stream to create new PDF document */ public byte[] CreatePdf() { using (MemoryStream ms = new MemoryStream()) { // step 1 using (Document document = new Document(new Rectangle(360, 360))) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, ms); // step 3 document.Open(); jsString = File.ReadAllText( Path.Combine(Utility.ResourceJavaScript, RESOURCE) ); writer.AddJavaScript(jsString); // step 4 // add the keys for the digits for (int i = 0; i < 10; i++) { AddPushButton( writer, digits[i], i.ToString(), "this.augment(" + i + ")" ); } // add the keys for the operators AddPushButton(writer, plus, "+", "this.register('+')"); AddPushButton(writer, minus, "-", "this.register('-')"); AddPushButton(writer, mult, "x", "this.register('*')"); AddPushButton(writer, div, ":", "this.register('/')"); AddPushButton(writer, equals, "=", "this.calculateResult()"); // add the other keys AddPushButton(writer, clearEntry, "CE", "this.reset(false)"); AddPushButton(writer, clear, "C", "this.reset(true)"); AddTextField(writer, result, "result"); AddTextField(writer, move, "move"); } return(ms.ToArray()); } }
public void MakePrintable(string sourcePath, string targetPath) { int pageNumber = 1; PdfReader reader = new PdfReader(sourcePath); Rectangle size = reader.GetPageSizeWithRotation(pageNumber); Document document = new Document(size); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(targetPath, FileMode.Create, FileAccess.Write)); document.Open(); PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer); writer.AddJavaScript(jAction); PdfContentByte cb = writer.DirectContent; document.NewPage(); PdfImportedPage page = writer.GetImportedPage(reader, pageNumber); cb.AddTemplate(page, 0, 0); reader.Close(); document.Close(); writer.Close(); document.Close(); }
public ValueCreationBlock() { filenameBlank = filename.Replace(".", "_Blank."); FileStream fs = new System.IO.FileStream(filenameBlank, System.IO.FileMode.Create); writer = PdfWriter.GetInstance(doc, fs); doc.Open(); cb = writer.DirectContent; BaseFont bfHelvetica = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false); Font helvetica12 = new Font(bfHelvetica, 12, Font.NORMAL, BaseColor.BLACK); PdfPTable table = new PdfPTable(2); table.TotalWidth = 570f; table.LockedWidth = true; //relative col widths in proportions - 1/3 and 2/3 float[] widths = new float[] { 2f, 3f }; table.SetWidths(widths); table.HorizontalAlignment = Element.ALIGN_CENTER; PdfPCell cell1 = new PdfPCell(new Phrase("Value Creation and Impact", new Font(Font.NORMAL, 10f, Font.NORMAL, BaseColor.WHITE))); cell1.PaddingLeft = 10; cell1.BackgroundColor = PDFColor.BCGGreen; cell1.Colspan = 3; cell1.Border = PdfPCell.NO_BORDER; cell1.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right table.AddCell(cell1); PdfPTable nested = new PdfPTable(1); //nested.TotalWidth = 270f; //nested.LockedWidth = true; //float[] widthforcol = new float[] { 100f, 170f}; //nested.SetWidths(widthforcol); PdfPCell cell2 = new PdfPCell(new Phrase("Develops clear recommendations with an action bias", new Font(Font.NORMAL, 10f, Font.NORMAL, BaseColor.BLACK))); cell2.PaddingLeft = 10; //cell2.Colspan = 2; cell2.BackgroundColor = BaseColor.LIGHT_GRAY; cell2.Border = PdfPCell.NO_BORDER; cell2.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right nested.AddCell(cell2); PdfPCell cell3 = new PdfPCell(new Phrase("Networks within client organization to understand agenda", new Font(Font.NORMAL, 10f, Font.NORMAL, BaseColor.BLACK))); cell3.PaddingLeft = 10; //cell3.Colspan = 2; cell3.BackgroundColor = BaseColor.LIGHT_GRAY; cell3.Border = PdfPCell.NO_BORDER; cell3.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right nested.AddCell(cell3); PdfPCell cell4 = new PdfPCell(new Phrase("Is able to assess implementation challenges", new Font(Font.NORMAL, 10f, Font.NORMAL, BaseColor.BLACK))); cell4.PaddingLeft = 10; //cell4.Colspan = 2; cell4.BackgroundColor = BaseColor.LIGHT_GRAY; cell4.Border = PdfPCell.NO_BORDER; cell4.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right nested.AddCell(cell4); PdfPCell cell5 = new PdfPCell(new Phrase("Applies expertise to generate superior and sustainable results for client; is committed to making change happen", new Font(Font.NORMAL, 10f, Font.NORMAL, BaseColor.BLACK))); cell5.PaddingLeft = 10; //cell5.Colspan = 2; cell5.BackgroundColor = BaseColor.LIGHT_GRAY; cell5.Border = PdfPCell.NO_BORDER; cell5.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right nested.AddCell(cell5); PdfPCell cell6 = new PdfPCell(new Phrase("Effectively transfers capabilities to client teams", new Font(Font.NORMAL, 10f, Font.NORMAL, BaseColor.BLACK))); cell6.PaddingLeft = 10; //cell6.Colspan = 2; cell6.BackgroundColor = BaseColor.LIGHT_GRAY; cell6.Border = PdfPCell.NO_BORDER; cell6.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right nested.AddCell(cell6); //Rectangle rect = new iTextSharp.text.Rectangle(10, 20, 30, 40); //var rf1 = new RadioCheckField(writer, rect, "cellRadioBox", "on"); //rf1.CheckType = RadioCheckField.TYPE_CHECK; //PdfFormField field = rf1.CheckField; string[] labels = { "NA", "1", "2", "3", "4", "5" }; BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED); // create a radio field spanning different pages PdfFormField radiogroup = PdfFormField.CreateRadioButton(writer, true); radiogroup.FieldName = "language"; //Rectangle rect = new Rectangle(40, 606, 60, 588); RadioCheckField radio; PdfFormField radiofield; Rectangle rect; for (int i = 0; i < labels.Length; ++i) { rect = new Rectangle(50 + i * 30, 705, 50 + (i + 1) * 30, 695);//PDFDocPageSize.RIGHT //rect = new Rectangle(40, 606, 60, 588); radio = new RadioCheckField(writer, rect, null, labels[i]); radio.BackgroundColor = new GrayColor(0.8f); radiofield = radio.RadioField; radiofield.PlaceInPage = 1; //radiofield.PlaceInPage= ++page; radiogroup.AddKid(radiofield); } var radioEvents = new iTextSharp.text.pdf.events.FieldPositioningEvents(writer, radiogroup); PdfPCell radioCell = new PdfPCell(); radioCell.CellEvent = radioEvents; nested.AddCell(radioCell); PdfPCell nesthousing = new PdfPCell(nested); nesthousing.Padding = 0f; table.AddCell(nesthousing); TextField textfield = new TextField(writer, new iTextSharp.text.Rectangle(10, 20, 30, 40), "cellTextBox"); PdfPCell tbCell = new PdfPCell(new Phrase(" ", helvetica12)); iTextSharp.text.pdf.events.FieldPositioningEvents events = new iTextSharp.text.pdf.events.FieldPositioningEvents(writer, textfield.GetTextField()); tbCell.CellEvent = events; table.AddCell(tbCell); doc.Add(table); this.doc.Close(); GetReader(); //Add common Javascript code writer.AddJavaScript("var requiredFields = ['text1', 'grp1'];"); string validateFunction = "function validate () { " + " for (i=0; i<requiredFields.length; i++) {" + " var grp = this.getField(requiredFields[i]); if (!grp || grp.value === null || grp.value == ''|| grp.value=='Off') { " + " app.alert('please select this '+ requiredFields[i]); return false; }}" + "return true}"; writer.AddJavaScript(validateFunction); //Close all the streams stamper.Close(); reader.Close(); doc.Close(); }
public TestCreatePDF() { filenameBlank = filename.Replace(".", "_Blank."); FileStream fs = new System.IO.FileStream(filenameBlank, System.IO.FileMode.Create); writer = PdfWriter.GetInstance(doc, fs); doc.Open(); cb = writer.DirectContent; Rectangle rect = new Rectangle(50, 700, 300, 600) { BorderWidth = .25f, Border = 255 }; cb.Rectangle(rect); cb.Stroke(); //Add text Font font3 = new Font(FontFactory.GetFont(FontFactory.HELVETICA, 1000, Font.NORMAL, BaseColor.BLACK)); Chunk chunk = new Chunk("Roopesh", new Font(FontFactory.GetFont(FontFactory.HELVETICA, 10, Font.NORMAL, BaseColor.BLUE))); Phrase phrase = new Phrase(chunk); ColumnText ctext = new ColumnText(cb); ctext.SetSimpleColumn(rect.Left + 5, rect.Top, rect.Right, rect.Bottom); ctext.SetText(phrase); ctext.Go(); this.doc.Close(); GetReader(); //Add TextBox rect = new Rectangle(rect.Left, rect.Top - 100, rect.Right, rect.Bottom - 100); TextField tf = new TextField(writer, rect, "text1") { Alignment = Element.ALIGN_LEFT | Element.ALIGN_TOP, BorderColor = BaseColor.BLACK, BorderStyle = PdfBorderDictionary.STYLE_SOLID, Text = "TextField" }; stamper.AddAnnotation(tf.GetTextField(), 1); //Add Radio rect = new Rectangle(rect.Left, rect.Top - 100, rect.Right, rect.Bottom - 25); PdfFormField group = PdfFormField.CreateRadioButton(writer, true); group.FieldName = "grp1"; for (int i = 0; i < 5; i++) { Rectangle radioRect = new Rectangle(rect.Left + i * 25, rect.Top, rect.Left + (i + 1) * 25, rect.Bottom); RadioCheckField radioField = new RadioCheckField(writer, radioRect, "chk" + i.ToString(), i.ToString()) { BorderColor = GrayColor.BLACK, CheckType = RadioCheckField.TYPE_CIRCLE, BorderStyle = PdfBorderDictionary.STYLE_SOLID }; group.AddKid(radioField.RadioField); } //group.SetAdditionalActions(PdfName.E, PdfAction.JavaScript("app.alert(validate);",writer)); stamper.AddAnnotation(group, 1); //Add submit button rect = new Rectangle(rect.Left, rect.Top - 100, rect.Right, rect.Bottom - 25); PushbuttonField button = new PushbuttonField(writer, rect, "postSubmit") { FontSize = 8, BackgroundColor = BaseColor.LIGHT_GRAY, BorderColor = GrayColor.BLACK, BorderWidth = 1f, BorderStyle = PdfBorderDictionary.STYLE_BEVELED, TextColor = GrayColor.GREEN, Text = "Submit", Visibility = PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT }; PdfFormField field = button.Field; String javascript = "validate();"; field.Action = PdfAction.JavaScript(javascript, writer); //field.Action = PdfAction.CreateSubmitForm( @"*****@*****.**", null, PdfAction.SUBMIT_HTML_FORMAT | PdfAction.SUBMIT_INCLUDE_NO_VALUE_FIELDS); stamper.AddAnnotation(field, 1); PdfAcroForm f = new PdfAcroForm(writer); //Add common Javascript code writer.AddJavaScript("var requiredFields = ['text1', 'grp1'];"); string validateFunction = "function validate () { " + " for (i=0; i<requiredFields.length; i++) {" + " var grp = this.getField(requiredFields[i]); if (!grp || grp.value === null || grp.value == ''|| grp.value=='Off') { " + " app.alert('please select this '+ requiredFields[i]); return false; }}" + "return true}"; writer.AddJavaScript(validateFunction); //Close all the streams stamper.Close(); reader.Close(); doc.Close(); }
//sends pdf to printer private void SendToPrinter() { FileStream fs = new FileStream(Server.MapPath("~/Report/nasser7.pdf"), FileMode.Create); PdfReader reader = new PdfReader(Server.MapPath("~/Report/nasser.pdf")); int pageCount = reader.NumberOfPages; Rectangle pageSize = reader.GetPageSize(1); // Set up Writer Document document = new Document(pageSize); // PdfDocument document = new PdfDocument(pageSize); PdfWriter writer = PdfWriter.GetInstance(document, fs); document.Open(); //Copy each page PdfContentByte content = writer.DirectContent; for (int i = 0; i < pageCount; i++) { document.NewPage(); // page numbers are one based PdfImportedPage page = writer.GetImportedPage(reader, i + 1); // x and y correspond to position on the page content.AddTemplate(page, 0, 0); } // Inert Javascript to print the document after a fraction of a second to allow time to become visible. string jsText = "var res = app.setTimeOut(‘var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);’, 200);"; //string jsTextNoWait = “var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);”; PdfAction js = PdfAction.JavaScript(jsText, writer); writer.AddJavaScript(js); document.Close(); // FileStream fs = new FileStream(Server.MapPath("~/Report/nasser6.pdf"), FileMode.Create); // PdfReader reader = new PdfReader(Server.MapPath("~/Report/nasser.pdf")); // int pageCount = reader.NumberOfPages; // Rectangle pageSize = reader.GetPageSize(1); // // Setup writer // Document document = new Document(pageSize); // // PdfDocument document = new PdfDocument(); // PdfWriter writer = PdfWriter.GetInstance(document, fs); // document.Open(); // // Copy each page // PdfContentByte content = writer.DirectContent; // for (int i = 0; i < pageCount; i++) // { // document.NewPage(); // PdfImportedPage page = writer.GetImportedPage(reader, i + 1); // page numbers are one-based // content.AddTemplate(page, 0, 0); // x and y correspond to position on the page? // } // // Insert JavaScript to print the document after a fraction of a second (allow time to become visible). //// string jsText = "var res = app.setTimeOut('var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);', 200);"; // string jsTextNoWait = "var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);"; // PdfAction js = PdfAction.JavaScript(jsTextNoWait, writer); // writer.AddJavaScript(js); // document.Close(); }
// --------------------------------------------------------------------------- /** * Creates a PDF document. */ public byte[] CreatePdf() { using (MemoryStream ms = new MemoryStream()) { using (Document document = new Document()) { PdfWriter writer = PdfWriter.GetInstance(document, ms); document.Open(); jsString = File.ReadAllText( Path.Combine(Utility.ResourceJavaScript, RESOURCE) ); writer.AddJavaScript(jsString); PdfContentByte canvas = writer.DirectContent; Font font = new Font(Font.FontFamily.HELVETICA, 18); Rectangle rect; PdfFormField field; PdfFormField radiogroup = PdfFormField.CreateRadioButton(writer, true); radiogroup.FieldName = "language"; RadioCheckField radio; for (int i = 0; i < LANGUAGES.Length; i++) { rect = new Rectangle(40, 806 - i * 40, 60, 788 - i * 40); radio = new RadioCheckField(writer, rect, null, LANGUAGES[i]); radio.BorderColor = GrayColor.GRAYBLACK; radio.BackgroundColor = GrayColor.GRAYWHITE; radio.CheckType = RadioCheckField.TYPE_CIRCLE; field = radio.RadioField; radiogroup.AddKid(field); ColumnText.ShowTextAligned( canvas, Element.ALIGN_LEFT, new Phrase(LANGUAGES[i], font), 70, 790 - i * 40, 0 ); } writer.AddAnnotation(radiogroup); PdfAppearance[] onOff = new PdfAppearance[2]; onOff[0] = canvas.CreateAppearance(20, 20); onOff[0].Rectangle(1, 1, 18, 18); onOff[0].Stroke(); onOff[1] = canvas.CreateAppearance(20, 20); onOff[1].SetRGBColorFill(255, 128, 128); onOff[1].Rectangle(1, 1, 18, 18); onOff[1].FillStroke(); onOff[1].MoveTo(1, 1); onOff[1].LineTo(19, 19); onOff[1].MoveTo(1, 19); onOff[1].LineTo(19, 1); onOff[1].Stroke(); RadioCheckField checkbox; for (int i = 0; i < LANGUAGES.Length; i++) { rect = new Rectangle(180, 806 - i * 40, 200, 788 - i * 40); checkbox = new RadioCheckField(writer, rect, LANGUAGES[i], "on"); // checkbox.CheckType = RadioCheckField.TYPE_CHECK; field = checkbox.CheckField; field.SetAppearance( PdfAnnotation.APPEARANCE_NORMAL, "Off", onOff[0] ); field.SetAppearance( PdfAnnotation.APPEARANCE_NORMAL, "On", onOff[1] ); writer.AddAnnotation(field); ColumnText.ShowTextAligned( canvas, Element.ALIGN_LEFT, new Phrase(LANGUAGES[i], font), 210, 790 - i * 40, 0 ); } rect = new Rectangle(300, 806, 370, 788); PushbuttonField button = new PushbuttonField(writer, rect, "Buttons"); button.BackgroundColor = new GrayColor(0.75f); button.BorderColor = GrayColor.GRAYBLACK; button.BorderWidth = 1; button.BorderStyle = PdfBorderDictionary.STYLE_BEVELED; button.TextColor = GrayColor.GRAYBLACK; button.FontSize = 12; button.Text = "Push me"; button.Layout = PushbuttonField.LAYOUT_ICON_LEFT_LABEL_RIGHT; button.ScaleIcon = PushbuttonField.SCALE_ICON_ALWAYS; button.ProportionalIcon = true; button.IconHorizontalAdjustment = 0; button.Image = Image.GetInstance( Path.Combine(Utility.ResourceImage, IMAGE) ); field = button.Field; field.Action = PdfAction.JavaScript("this.showButtonState()", writer); writer.AddAnnotation(field); } return(ms.ToArray()); } }
public ActionResult printPDF() { string pdfBody = string.Empty; pdfBody += "<table>"; pdfBody += "<tr>"; pdfBody += "<td> C </ td >"; pdfBody += "<td> RoseWater</td>"; pdfBody += "<td></td>"; pdfBody += "</tr>"; pdfBody += "<tr>"; pdfBody += "<td>Date:01/06/201</td>"; pdfBody += "<td>Name:Nasser</td>"; pdfBody += "<td>Te:1234566</td>"; pdfBody += "</tr>"; foreach (var itm in db.Customers.OrderBy(x => x.CustName).ToList()) { pdfBody += "<tr>"; pdfBody += "<td>" + itm.CustName + "</td>"; pdfBody += "<td>" + itm.Tel + "</td>"; pdfBody += "<td>" + itm.CustId + "</td>"; pdfBody += "</tr>"; } pdfBody += "</table>"; Document document = new Document(); //string filenm = "UserList.pdf"; string filenm = "BillNo-" + DateTime.Now.Ticks + ".pdf"; var fpath = HttpContext.Server.MapPath("~/Documents/PDFDocuments/"); //PngWriter.GetInstance(document, new FileStream(fpath + filenm, FileMode.Create)); PdfWriter oPdfWriter = PdfWriter.GetInstance(document, new FileStream(fpath + filenm, FileMode.Create)); document.Open(); //If you want to add phrase: Phrase titl = new Phrase("\nCustomer Copy\n"); titl.Font.SetStyle(Font.BOLD); document.Add(titl); iTextSharp.text.html.simpleparser.StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet(); iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document); hw.Parse(new StringReader(pdfBody)); var logo = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Content/images/logo.png")); logo.SetAbsolutePosition(300, 750); document.Add(logo); string jsText = "var res = app.setTimeOut(‘var pp = this.getPrintParams();pp.interactive = pp.constants.interactionLevel.full;this.print(pp);’, 200);"; PdfAction js = PdfAction.JavaScript(jsText, oPdfWriter); oPdfWriter.AddJavaScript(js); document.Close(); Response.ClearContent(); Response.ClearHeaders(); Response.AddHeader("Content-Disposition", "inline;filename=" + filenm + ""); Response.ContentType = "application/pdf"; Response.WriteFile(HttpContext.Server.MapPath("~/Documents/PDFDocuments/") + filenm); Response.Flush(); Response.Clear(); //printMyPDF("UserList.pdf"); ViewBag.myPDF = filenm; return(View()); }
protected void btnprintq_Click(object sender, EventArgs e) { Warning[] warnings; string[] streamids; string mimeType; string encoding; string extension; byte[] bytes = rptReciptPrint.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamids, out warnings); FileStream fs = new FileStream(HttpContext.Current.Server.MapPath("output.pdf"), FileMode.Create); fs.Write(bytes, 0, bytes.Length); fs.Close(); //Open exsisting pdf Document document = new Document(PageSize.LETTER); PdfReader reader = new PdfReader(HttpContext.Current.Server.MapPath("output.pdf")); //Getting a instance of new pdf wrtiter string uploadPath = Server.MapPath("~/StudentRecipts"); if (!Directory.Exists(uploadPath)) { Directory.CreateDirectory(uploadPath); } string stdpath = Server.MapPath("~/StudentRecipts/" + hdnAdmissionid.Value); if (!Directory.Exists(stdpath)) { Directory.CreateDirectory(stdpath); } string intallno = Request.QueryString["InstallmentNo"].ToString(); string filename = hdnAdmissionid.Value + "_" + h3StudentName.InnerText + "_" + intallno + ".pdf"; string path = Path.Combine(stdpath, filename); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create)); document.Open(); PdfContentByte cb = writer.DirectContent; int i = 0; int p = 0; int n = reader.NumberOfPages; Rectangle psize = reader.GetPageSize(1); float width = psize.Width; float height = psize.Height; //Add Page to new document while (i < n) { document.NewPage(); p++; i++; PdfImportedPage page1 = writer.GetImportedPage(reader, i); cb.AddTemplate(page1, 0, 0); } //Attach javascript to the document PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer); writer.AddJavaScript(jAction); document.Close(); //Attach pdf to the iframe frmPrint.Attributes["src"] = "~/StudentRecipts/" + hdnAdmissionid.Value + "/" + filename; }
// --------------------------------------------------------------------------- public void Write(Stream stream) { // step 1 using (Document document = new Document()) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, stream); writer.SetPdfVersion(PdfWriter.PDF_VERSION_1_7); writer.AddDeveloperExtension( PdfDeveloperExtension.ADOBE_1_7_EXTENSIONLEVEL3 ); // step 3 document.Open(); // step 4 writer.AddJavaScript(File.ReadAllText(JS)); // we prepare a RichMediaAnnotation RichMediaAnnotation richMedia = new RichMediaAnnotation( writer, new Rectangle(36, 560, 561, 760) ); // we embed the swf file PdfFileSpecification fs = PdfFileSpecification.FileEmbedded( writer, RESOURCE, "FestivalCalendar2.swf", null ); // we declare the swf file as an asset PdfIndirectReference asset = richMedia.AddAsset( "FestivalCalendar2.swf", fs ); // we create a configuration RichMediaConfiguration configuration = new RichMediaConfiguration( PdfName.FLASH ); RichMediaInstance instance = new RichMediaInstance(PdfName.FLASH); instance.Asset = asset; configuration.AddInstance(instance); // we add the configuration to the annotation PdfIndirectReference configurationRef = richMedia.AddConfiguration( configuration ); // activation of the rich media RichMediaActivation activation = new RichMediaActivation(); activation.Configuration = configurationRef; richMedia.Activation = activation; // we add the annotation PdfAnnotation richMediaAnnotation = richMedia.CreateAnnotation(); richMediaAnnotation.Flags = PdfAnnotation.FLAGS_PRINT; writer.AddAnnotation(richMediaAnnotation); String[] days = new String[] { "2011-10-12", "2011-10-13", "2011-10-14", "2011-10-15", "2011-10-16", "2011-10-17", "2011-10-18", "2011-10-19" }; for (int i = 0; i < days.Length; i++) { Rectangle rect = new Rectangle(36 + (65 * i), 765, 100 + (65 * i), 780); PushbuttonField button = new PushbuttonField(writer, rect, "button" + i); button.BackgroundColor = new GrayColor(0.75f); button.BorderStyle = PdfBorderDictionary.STYLE_BEVELED; button.TextColor = GrayColor.GRAYBLACK; button.FontSize = 12; button.Text = days[i]; button.Layout = PushbuttonField.LAYOUT_ICON_LEFT_LABEL_RIGHT; button.ScaleIcon = PushbuttonField.SCALE_ICON_ALWAYS; button.ProportionalIcon = true; button.IconHorizontalAdjustment = 0; PdfFormField field = button.Field; RichMediaCommand command = new RichMediaCommand( new PdfString("getDateInfo") ); command.Arguments = new PdfString(days[i]); RichMediaExecuteAction action = new RichMediaExecuteAction( richMediaAnnotation.IndirectReference, command ); field.Action = action; writer.AddAnnotation(field); } TextField text = new TextField( writer, new Rectangle(36, 785, 559, 806), "date" ); text.Options = TextField.READ_ONLY; writer.AddAnnotation(text.GetTextField()); } }