public void ProcessRequest(HttpContext context) { try { string Rut = context.Request.QueryString["Rut"]; string Mes = context.Request.QueryString["Mes"]; string Anio = context.Request.QueryString["Anio"]; string usuario = context.Request.QueryString["Usuario"]; string contrasena = context.Request.QueryString["Clave"]; string retorno = "ERROR"; ConexionController conexion = new ConexionController(); try { if (!string.IsNullOrEmpty(usuario) && !string.IsNullOrEmpty(contrasena)) { retorno = conexion.connectionsSAP(usuario, contrasena); } if (string.IsNullOrEmpty(retorno)) { RfcDestination SapRfcDestination = RfcDestinationManager.GetDestination(conexion.connectorConfig); RfcRepository SapRfcRepository = SapRfcDestination.Repository; IRfcFunction BapiGetUser = SapRfcRepository.CreateFunction("ZHR_LIQ_SUE"); BapiGetUser.SetValue("I_RUT", Rut); BapiGetUser.SetValue("I_MES", Mes); BapiGetUser.SetValue("I_ANO", Anio); BapiGetUser.Invoke(SapRfcDestination); Byte[] bytes = (Byte[])BapiGetUser.GetValue("PDF_LIQUI"); using (MemoryStream input = new MemoryStream(bytes)) { using (MemoryStream output = new MemoryStream()) { string password = Rut; PdfReader reader = new PdfReader(input); PdfEncryptor.Encrypt(reader, output, true, password, password, PdfWriter.ALLOW_SCREENREADERS); bytes = output.ToArray(); } } context.Response.Buffer = true; context.Response.Charset = ""; context.Response.Cache.SetCacheability(HttpCacheability.NoCache); context.Response.ContentType = "application/pdf"; context.Response.BinaryWrite(bytes); context.Response.Flush(); context.Response.End(); } } catch (Exception e) { } finally { } } catch (Exception ex) { } }
/// <summary> /// Load pdf file by stream /// </summary> /// <param name="fileName"></param> /// <returns></returns> private bool LoadFileByStream(string fileName) { bool isrmsProtect = true; Stream stream = null; byte[] license = null; string rmsUserPassword = string.Empty; if (rmsUserpEncrypt) { try { //RMS化PDFファイルから、RMSライセンス情報と、暗号化された本文情報を分割する //RMS署名情報から、RMSサーバー情報を抽出する //RMSサーバーでの認証 //RMSサーバーからRMSライセンスの取得 license = SafeFileApiNativeMethods.IpcfGetSerializedLicenseFromFile(fileName); } catch (Exception ex) { isrmsProtect = false; } } if (isrmsProtect && rmsUserpEncrypt) { try { rmsUserPassword = GenerateRandom(32); //RMSライセンスから、復号鍵の抽出 SafeInformationProtectionKeyHandle keyHandle = SafeNativeMethods.IpcGetKey(license, false, false, true, this); //RMSライセンスから、権利リストの抽出 //Collection<UserRights> userRights = new Collection<UserRights>(); //userRights = SafeNativeMethods.IpcGetSerializedLicenseUserRightsList(license, keyHandle); bool accessGranted = SafeNativeMethods.IpcAccessCheck(keyHandle, "VIEW"); //本文情報を復号鍵で、復号 tempFile = GenerateRandom(10); //一時フォルダ作成 add kondo System.IO.Directory.CreateDirectory(Path.GetTempPath() + @"PDFViewer\"); tempFile = Path.GetTempPath() + @"PDFViewer\" + tempFile; Stream outPutRmsStream = new FileStream(tempFile, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite); stream = new FileStream(fileName, FileMode.Open); if (accessGranted) { SafeFileApiNativeMethods.IpcfDecryptFileStream(stream, fileName, SafeFileApiNativeMethods.DecryptFlags.IPCF_DF_FLAG_DEFAULT, false, false, false, this, ref outPutRmsStream); } outPutRmsStream.Close(); outPutRmsStream.Dispose(); PdfReader reader = new PdfReader(tempFile); outPutStream = new FileStream(tempFile + ".tmp", FileMode.Create, FileAccess.ReadWrite, FileShare.None); PdfEncryptor.Encrypt(reader, outPutStream, false, rmsUserPassword, "", 0); rmsUserpEncrypt = false; reader.Close(); reader.Dispose(); File.Delete(tempFile); } catch (InformationProtectionException ex) { //DirectoryDelete MSIPC DeleteDirectorySelect(true); isrmsProtect = false; MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK); } catch (Exception ex) { isrmsProtect = false; } } try { if (isrmsProtect) { pdfDoc.LoadPDF(tempFile + ".tmp"); } else { pdfDoc.LoadPDF(fileName); } if (stream != null) { stream.Close(); stream.Dispose(); } return(true); } catch (System.Security.SecurityException sex) { if (stream != null) { stream.Close(); stream.Dispose(); } if (pdfDoc != null) { pdfDoc.Dispose(); pdfDoc = null; } pdfDoc = new PDFWrapper(); if (!rmsUserpEncrypt) { pdfDoc.UserPassword = rmsUserPassword; } else { String password = Interaction.InputBox("Please enter the document password:"******"Document Password", ""); if (password.Equals(string.Empty)) { return(false); } pdfDoc.UserPassword = password; } return(LoadFileByStream(fileName)); } catch (Exception ex) { //MessageBox.Show(ex.ToString()); return(false); } }
public string GetReportData() { int FileCount = 0; try { string contentType = string.Empty; contentType = "application/pdf"; DataSet thisDataSet = GetIR(Session["BRCD"].ToString(), TxtMemNo.Text); if (thisDataSet == null || thisDataSet.Tables[0].Rows.Count == 0) { WebMsgBox.Show("Sorry No Record found......!!", this.Page); } else { DataTable DTAC = new DataTable(); int ArrIndex = 0; DTAC = thisDataSet.Tables[0]; DataTable DataT = DTAC.Clone(); string[] AccArray = new string[1000000]; for (int i = 0; i < DTAC.Rows.Count; i++) { if (i != 0) { ArrIndex = GetArrayElementIndex(AccArray); if (AccArray[ArrIndex - 1].ToString() != DTAC.Rows[i]["ACCNO"].ToString()) { AccArray[ArrIndex] = DTAC.Rows[i]["ACCNO"].ToString(); } else { ArrIndex = GetArrayElementIndex(AccArray); } } else { AccArray[i] = DTAC.Rows[i]["ACCNO"].ToString(); } } int Count = 0; Count = GetArrayElementIndex(AccArray); int CountAcc = 0; int DTACCount = 0; int OrgCountRows = (DTAC.Rows.Count) - 1; int FOrgCountRows = OrgCountRows; string folderName = @"c:\I Register\"; foreach (DataRow dr in DTAC.Rows) { if (DTAC.Rows[FOrgCountRows - OrgCountRows]["ACCNO"].ToString() == AccArray[CountAcc].ToString()) { DataT.ImportRow(dr); if ((FOrgCountRows - OrgCountRows) != (DTAC.Rows.Count) - 1) { OrgCountRows--; } DTACCount++; } if (DTAC.Rows[FOrgCountRows - OrgCountRows]["ACCNO"].ToString() != AccArray[CountAcc].ToString()) { string fileName = "_" + AccArray[CountAcc] + ".pdf"; //PWD = DataT.Rows[0]["CalcAccID_PW"].ToString() != null ? DataT.Rows[0]["CalcAccID_PW"].ToString() : "101010"; CountAcc++; string extension; string encoding; string mimeType; string[] streams; Warning[] warnings; LocalReport report = new LocalReport(); report.ReportPath = Server.MapPath("~/RptIRegister.rdlc"); ReportDataSource rds = new ReportDataSource(); rds.Name = "ReportDS"; rds.Value = DataT; report.DataSources.Add(rds); byte[] mybytes = report.Render("PDF", null, out extension, out encoding, out mimeType, out streams, out warnings); //for exporting to PDF if (!System.IO.File.Exists(folderName)) { using (System.IO.MemoryStream input = new System.IO.MemoryStream(mybytes)) { using (System.IO.MemoryStream output = new System.IO.MemoryStream()) { PdfReader reader = new PdfReader(input); PdfEncryptor.Encrypt(reader, output, true, PWD, PWD, PdfWriter.ALLOW_SCREENREADERS); mybytes = output.ToArray(); using (FileStream fs = File.Create(folderName + fileName)) //ANKITA c:\\targetfolder\ { fs.Write(mybytes, 0, mybytes.Length); } Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.BinaryWrite(mybytes); } } } else { WebMsgBox.Show("File already exists.", this.Page); } Response.Buffer = true; Response.Clear(); Response.ContentType = contentType; Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName); Response.WriteFile(folderName + fileName); DataT.Clear(); } } string fileName1 = "_" + AccArray[CountAcc] + ".pdf"; CountAcc++; string extension1; string encoding1; string mimeType1; string[] streams1; Warning[] warnings1; //PWD = DataT.Rows[0]["CalcAccID_PW"].ToString() != null ? DataT.Rows[0]["CalcAccID_PW"].ToString() : "101010"; LocalReport report1 = new LocalReport(); report1.ReportPath = Server.MapPath("~/RptIRegister.rdlc"); ReportDataSource rds1 = new ReportDataSource(); rds1.Name = "ReportDS";//This refers to the dataset name in the RDLC file rds1.Value = DataT; report1.DataSources.Add(rds1); byte[] mybytes1 = report1.Render("PDF", null, out extension1, out encoding1, out mimeType1, out streams1, out warnings1); //for exporting to PDF if (!System.IO.File.Exists(folderName)) { using (System.IO.MemoryStream input = new System.IO.MemoryStream(mybytes1)) { using (System.IO.MemoryStream output = new System.IO.MemoryStream()) { PdfReader reader = new PdfReader(input); PdfEncryptor.Encrypt(reader, output, true, PWD, PWD, PdfWriter.ALLOW_SCREENREADERS); mybytes1 = output.ToArray(); using (FileStream fs = File.Create(folderName + fileName1)) //ANKITA c:\\targetfolder\ { fs.Write(mybytes1, 0, mybytes1.Length); } Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.BinaryWrite(mybytes1); } } } else { WebMsgBox.Show("File already exists.", this.Page); } Response.Buffer = true; Response.Clear(); Response.ContentType = contentType; Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName1); Response.WriteFile(folderName + fileName1); DataT.Clear(); FileCount = Directory.EnumerateFiles(@"c:\I Register\", "*.pdf").Count(); } } catch (System.Threading.ThreadAbortException lException) { } return(Convert.ToString(FileCount)); }
public HttpResponseMessage GetstatementFor(string filename) { Paragraph paragraph = new Paragraph("Digipment Digital Solutions Pvt Ltd, Pune 411033"); var dateString = DateTime.Now.ToString("yyyyMMdd"); string bookName = filename + dateString + ".pdf"; string filepath = "~/downloadfile/"; string imageURL = System.Web.Hosting.HostingEnvironment.MapPath(filepath + "/tollpayoldlogo.jpg"); iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL); //Resize image depend upon your need jpg.ScaleToFit(140f, 120f); //Give space before image jpg.SpacingBefore = 10f; //Give some space after the image jpg.SpacingAfter = 1f; jpg.Alignment = Element.ALIGN_CENTER; //Create document Document doc = new Document(PageSize.A4); //Create PDF Table PdfPTable tableLayout = new PdfPTable(4); //Create a PDF file in specific path PdfWriter.GetInstance(doc, new FileStream(System.Web.Hosting.HostingEnvironment.MapPath(filepath + bookName), FileMode.Create)); //Open the PDF document doc.Open(); doc.AddHeader("H1", "Digipment Digital Solutions Pvt Ltd, Pune 411033"); doc.AddCreator("DPTP"); doc.Add(paragraph); doc.Add(jpg); //Add Content to PDF doc.Add(Add_Content_To_PDF(tableLayout)); // Closing the document doc.Close(); using (Stream input = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath(filepath + bookName), FileMode.Open, FileAccess.Read, FileShare.Read)) { using (Stream output = new FileStream(System.Web.Hosting.HostingEnvironment.MapPath(filepath + "Encry_" + bookName), FileMode.Create, FileAccess.Write, FileShare.None)) { PdfReader reader = new PdfReader(input); PdfEncryptor.Encrypt(reader, output, true, "secret", "secret", PdfWriter.ALLOW_SCREENREADERS); } } var dataBytes = File.ReadAllBytes(System.Web.Hosting.HostingEnvironment.MapPath(filepath + "Encry_" + bookName)); //adding bytes to memory stream var dataStream = new MemoryStream(dataBytes); HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK); httpResponseMessage.Content = new StreamContent(dataStream); httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); httpResponseMessage.Content.Headers.ContentDisposition.FileName = "Encry_" + bookName; httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); return(httpResponseMessage); }
//private static Column CreateColumnData(UInt32 StartColumnIndex, UInt32 EndColumnIndex, double ColumnWidth) // getting width of column //{ // Column column; // column = new Column(); // column.Min = StartColumnIndex; // column.Max = EndColumnIndex; // column.Width = ColumnWidth; // column.CustomWidth = true; // return column; //} protected void PDF_Click(object sender, EventArgs e) { try { if (Session["Data"] == null) { Response.Write("No data to generate Excel"); return; } Response.ContentType = "application/pdf"; //Response.AddHeader("content-disposition", "attachment;filename=Cash_Recent_Health_Report_" + DateTime.Now.ToString("dd-MM-yy_HH:mm") + ".xlsx"); Response.Cache.SetCacheability(HttpCacheability.NoCache); MemoryStream memoryStream = new MemoryStream(); //creating pdf document Document pdfDoc = new Document(PageSize.A4.Rotate(), 5f, 5f, 10f, 5f); // getting writer for pdf PdfWriter.GetInstance(pdfDoc, Response.OutputStream); PdfWriter.GetInstance(pdfDoc, memoryStream); Paragraph para = new Paragraph(); Paragraph para1 = new Paragraph(); Paragraph para2 = new Paragraph(); para.Alignment = 1; para.Font = FontFactory.GetFont(FontFactory.TIMES_ITALIC, 30f, BaseColor.BLACK); para.SpacingBefore = 50; para.SpacingAfter = 50; para.Add("Terminal Secure Server"); DataSet dataSet = (DataSet)Session["Data"]; PdfPTable table = new PdfPTable(dataSet.Tables[0].Columns.Count); // -2 new //spacing before and after table table.TotalWidth = 823f; table.LockedWidth = true; table.SpacingBefore = 5f; table.SpacingAfter = 5f; table.HorizontalAlignment = 0; PdfPCell cell = new PdfPCell(new Phrase()); int columnscount = dataSet.Tables[0].Columns.Count; string header1 = null; string header2 = null; header1 = " Terminal Secure Server -Device REPORT GENERATED ON " + DateTime.Now.ToString("dd MMM yyyy, HH:mm tt"); header2 = "REPORT"; Response.AddHeader("content-disposition", "attachment;filename=TSS_Device_Report_" + Modefilter.SelectedValue + "_" + DateTime.Now.ToString("dd-MM-yy_HH:mm") + ".pdf"); table.AddCell(GetCell(header1, columnscount, 1)); table.AddCell(GetCell(header2, columnscount, 2)); for (int j = 1; j <= columnscount; j++) { table.AddCell(GetCell(dataSet.Tables[0].Columns[j - 1].ColumnName.ToString(), 3)); // } foreach (DataRow row in dataSet.Tables[0].Rows) { //char b = 'A'; //string str = b + "" + k; for (int i = 0; i < dataSet.Tables[0].Columns.Count; i++) { table.AddCell(GetCell(row[i].ToString(), 4)); } } string imageURL = Server.MapPath(".") + "\\images\\LipiBlue.png"; iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL); jpg.ScaleToFit(140f, 120f); jpg.SpacingBefore = 10f; jpg.SpacingAfter = 1f; jpg.Alignment = Element.ALIGN_MIDDLE; pdfDoc.Open(); pdfDoc.Add(para); pdfDoc.Add(jpg); pdfDoc.Add(table); pdfDoc.Close(); byte[] bytes = memoryStream.ToArray(); memoryStream.Close(); using (MemoryStream input = new MemoryStream(bytes)) { using (MemoryStream output = new MemoryStream()) { string password = "******"; PdfReader reader = new PdfReader(input); PdfEncryptor.Encrypt(reader, output, true, password, password, PdfWriter.ALLOW_SCREENREADERS); bytes = output.ToArray(); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.BinaryWrite(bytes); Response.End(); //Response.Write(pdfDoc); //Response.End(); } } } catch (Exception ex) { } }
protected void btnEmail_Click(object sender, EventArgs e) { try { string checkedRequiredField = ""; DataTable dt = new DataTable(); Report.LoadSourceDataSet(ref checkedRequiredField, ref dt); foreach (DataRow dR in dt.Rows) { string email = dR["OfficialEmail"].ToString().Trim(); if (email.IsNullOrEmpty()) { continue; } Microsoft.Reporting.WebForms.ReportViewer rview = new Microsoft.Reporting.WebForms.ReportViewer(); rview.LocalReport.ReportPath = Session["reportPath"].ToString(); DataTable dt1 = new DataTable(); Report.LoadSourceDataSet(dR["EmpKey"].ToString(), ref dt1); ReportDataSource rdSource = null; //foreach (DataTable dtTable in Report.dsSource.Tables) //{ rdSource = new ReportDataSource(); rdSource.Name = dt1.TableName; rdSource.Value = dt1.DefaultView; rview.LocalReport.DataSources.Add(rdSource); //} string mimeType, encoding, extension; string[] streamids; Microsoft.Reporting.WebForms.Warning[] warnings; string format = "PDF"; byte[] bytes = rview.LocalReport.Render(format, "", out mimeType, out encoding, out extension, out streamids, out warnings); using (MemoryStream input = new MemoryStream(bytes)) { using (MemoryStream output = new MemoryStream()) { string password = "******"; PdfReader reader = new PdfReader(input); PdfEncryptor.Encrypt(reader, output, true, password, password, PdfWriter.ALLOW_SCREENREADERS); bytes = output.ToArray(); //Response.ContentType = "application/pdf"; //Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf"); //Response.Cache.SetCacheability(HttpCacheability.NoCache); //Response.BinaryWrite(bytes); //Response.End(); } } //save the pdf byte to the folder string savePath = ConfigurationManager.AppSettings["PaySlipFile"]; var path = System.Web.HttpContext.Current.Server.MapPath(savePath) + dR["EmpKey"].ToString() + "-" + dR["EmpName"].ToString() + ".pdf"; //var fullFileName = path + fileInfo.Extension; FileStream fs = new FileStream(path, FileMode.Create); byte[] data = new byte[fs.Length]; fs.Write(bytes, 0, bytes.Length); fs.Close(); //SendEmailWithReportAttachment obj = new SendEmailWithReportAttachment(); //obj.Email(dR["EmpKey"].ToString(), email, path); MailMessage msg = new MailMessage(); //msg.To.Add("*****@*****.**"); msg.To.Add(email); MailAddress frmAdd = new MailAddress("*****@*****.**"); msg.From = frmAdd; ////Check user enter CC address or not //if (ccId != "") //{ // msg.CC.Add(ccId); //} ////Check user enter BCC address or not //if (bccId != "") //{ // msg.Bcc.Add(bccId); //} msg.Subject = "Pay Slip"; //Check for attachment is there //if (FileUpload1.HasFile) //{ // msg.Attachments.Add(new Attachment(FileUpload1.PostedFile.InputStream, FileUpload1.FileName)); //} msg.IsBodyHtml = true; msg.Body = "This is system generated mail."; Attachment attach = new Attachment(path); msg.Attachments.Add(attach); //MailAttachment attachment = new MailAttachment(Server.MapPath("test.txt")); //create the attachment //mail.Attachments.Add(attachment); //add the attachment //SmtpClient mailClient = new SmtpClient("smtp.mail.yahoo.com", 25); SmtpClient mailClient = new SmtpClient("*****@*****.**", 1408); NetworkCredential NetCrd = new NetworkCredential("*****@*****.**", "@ukhiya1*44"); mailClient.UseDefaultCredentials = false; mailClient.Credentials = NetCrd; mailClient.EnableSsl = true; mailClient.DeliveryMethod = SmtpDeliveryMethod.Network; mailClient.Send(msg); attach.Dispose(); msg.Dispose(); mailClient.Dispose(); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } } } catch (Exception ex) { ((PageBase)this.Page).ErrorMessage = (ExceptionHelper.getExceptionMessage(ex)); } }