//Add Text to PDF private void add_text_to_pdf(string pdf_path, string new_pdf_path, string text1) { string oldFile = pdf_path; string newFile = new_pdf_path; // open the reader PdfReader reader = new PdfReader(oldFile); Rectangle size = reader.GetPageSizeWithRotation(1); Document document = new Document(size); FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write); PdfWriter writer = PdfWriter.GetInstance(document, fs); document.Open(); // the pdf content PdfContentByte cb = writer.DirectContent; // create the new page and add it to the pdf PdfImportedPage page; for (int i = 1; i <= reader.NumberOfPages; i++) { page = writer.GetImportedPage(reader, i); var pageRotation = reader.GetPageRotation(i); var pageWidth = reader.GetPageSizeWithRotation(i).Width; var pageHeight = reader.GetPageSizeWithRotation(i).Height; switch (pageRotation) { case 0: cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); break; case 90: cb.AddTemplate(page, 0, -1f, 1f, 0, 0, pageHeight); break; case 180: cb.AddTemplate(page, -1f, 0, 0, -1f, pageWidth, pageHeight); break; case 270: cb.AddTemplate(page, 0, 1f, -1f, 0, pageWidth, 0); break; default: cb.AddTemplate(page, 0, 0); break; } // select the font properties BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.SetColorFill(BaseColor.BLUE); //cb.SetFontAndSize(bf, 25); float text_x = 0f, text_y = 0f; if (pageWidth < 850) { text_x = 450f; text_y = 120f; cb.SetFontAndSize(bf, 20); } else { text_x = 600f; text_y = 160f; cb.SetFontAndSize(bf, 25); } // write the text in the pdf content cb.BeginText(); string text = string.Format("Width: {0}, Height: {1}", pageWidth, pageHeight); // put the alignment and coordinates here cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, text_x, text_y, 0); cb.EndText(); document.NewPage(); } // close the streams and voilá the file should be changed :) document.Close(); fs.Close(); writer.Close(); reader.Close(); }
/// /// Merges the Docs and renders the destinationFile /// private void MergeDocs() { try { Boolean isStart = true; Int32 countFiles = 1; Int32 countProcessedFiles = 1; Int32 countMerge = 1; Int32 n = 0; Int32 rotation = 0; Document document = null; PdfContentByte cb = null; PdfImportedPage page; PdfWriter writer = null; //Sort file list fileList.Sort(); //Loops for each file that has been listed foreach (String filename in fileList) { if (isStart) { //Create a Docuement-Object document = new Document(); //We create a writer that listens to the document writer = PdfWriter.GetInstance(document, new FileStream(destinationfile + "\\" + s_fileName + "_" + countMerge + ".pdf", FileMode.Create)); ////Reset Status //labelStatus.Text = ""; //Application.DoEvents(); //Open the document document.Open(); cb = writer.DirectContent; n = 0; rotation = 0; countFiles = 1; countMerge++; isStart = false; } //We create a reader for the document PdfReader reader = new PdfReader(filename); //Gets the number of pages to process n = reader.NumberOfPages; Int32 i = 0; while (i < n) { i++; document.SetPageSize(reader.GetPageSizeWithRotation(1)); document.NewPage(); //Insert to Destination on the first page if (i == 1) { Chunk fileRef = new Chunk(" "); fileRef.SetLocalDestination(filename); document.Add(fileRef); } page = writer.GetImportedPage(reader, i); rotation = reader.GetPageRotation(i); if (rotation == 90 || rotation == 270) { cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height); } else { cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); } } //labelFilesCount.Text = "Files merged: " + String.Format("{0:0,0}", countProcessedFiles); countFiles++; countProcessedFiles++; if (countFiles > i_Split || fileList.IndexOf(filename) == fileList.Count - 1) { // labelStatus.Text = "Closing document..."; // Application.DoEvents(); document.Close(); isStart = true; } } } catch (Exception ex) { throw new Exception(ex.ToString() + "-->MergeDocs"); } }
public string GenerarPDF_Documento(bool Mostrar) { _ServerPath = _Server.MapPath(".").Replace("\\Documentos", string.Empty); _tempFilePath = string.Format("{0}\\PDFDocs\\tempPDF", _ServerPath); _ImagenApliredPath = string.Format("{0}\\LogosEmpresa\\LogoAplired.png", _ServerPath); try { if (!Directory.Exists(_tempFilePath)) { Directory.CreateDirectory(_tempFilePath); } long IdDocumento = long.Parse(Session["IdDocumento"].ToString()); long IdEmpresa = long.Parse(Session["IdEmpresa"].ToString()); long IdUsuario = long.Parse(Session["UserId"].ToString()); long IdTipoDocumento = long.Parse(Session["IdTipoDocumento"].ToString()); eSystemModules Modulo = (eSystemModules)IdTipoDocumento; string TipoDocumento = Modulo.ToString(); string NombreModulo = string.Empty; if (GenerarArchivosTemporales()) { List <PdfReader> reader = new List <PdfReader>(); PdfImportedPage page; int rotation; int i = 0; int n = 0; _TableOfContent = new List <objContenido>(); _ActualPageWidth = PageSize.LETTER.Width; using (Entities db = new Entities()) { tblDocumento dataDocumento = (from d in db.tblDocumento where d.IdEmpresa == IdEmpresa && d.IdDocumento == IdDocumento && d.IdTipoDocumento == IdTipoDocumento select d).FirstOrDefault(); eEstadoDocumento EstadoDocumento = (eEstadoDocumento)dataDocumento.IdEstadoDocumento; //string _docPassowrd = string.Format("BCMWEB.{0}.{1}", (dataDocumento.Negocios ? "N" : "T"), IdEmpresa.ToString("000")); //string _ownerPassowrd = string.Format("{0}.{1}.{2}.BCMWEB", TipoDocumento, (dataDocumento.Negocios ? "N" : "T"), IdEmpresa.ToString("000")); string _CodigoInforme = string.Format("{0}_{1}_{2}_{3}_{4}.{5}", TipoDocumento, IdEmpresa.ToString(), dataDocumento.NroDocumento.ToString("#000"), (EstadoDocumento == eEstadoDocumento.Certificado ? dataDocumento.FechaEstadoDocumento.ToString("MM-yyyy") : DateTime.Now.ToString("MM-yyyy")), dataDocumento.VersionOriginal, dataDocumento.NroVersion); _FileName = string.Format("{0}.pdf", _CodigoInforme.Replace("-", "_")); _pathFile = String.Format("{0}\\PDFDocs\\{1}", _ServerPath, _FileName); _strDocURL = String.Format("{0}/PDFDocs/{1}", _AppUrl, _FileName); string _LogoEmpresaPath = string.Format("{0}{1}", _ServerPath, dataDocumento.tblEmpresa.LogoURL.Replace("/", "\\").Replace("~", "")); _ImagenEmpresa = Image.GetInstance(_LogoEmpresaPath); _ImagenEmpresa.Alignment = Element.ALIGN_CENTER; if (File.Exists(_pathFile)) { File.Delete(_pathFile); } string _pattern = string.Format("tmp{0}_{1}???_{2}*.pdf", TipoDocumento, IdEmpresa.ToString("000"), dataDocumento.IdDocumento.ToString("000")); List <string> _pdfFiles = Directory.GetFiles(_tempFilePath, _pattern, SearchOption.AllDirectories).OrderBy(q => q).ToList(); _Documento = new Document(); _pdfWrite = PdfWriter.GetInstance(_Documento, new FileStream(_pathFile, FileMode.Create)); _pdfWrite.PageEvent = _PDF_Events; //_pdfWrite.SetEncryption( // System.Text.Encoding.UTF8.GetBytes(_docPassowrd) // , System.Text.Encoding.UTF8.GetBytes(_ownerPassowrd) // , PdfWriter.AllowPrinting // , PdfWriter.ENCRYPTION_AES_256); string[] docKeywords = new string[] { _FileName, dataDocumento.tblEmpresa.NombreComercial, TipoDocumento, }; _Documento.Open(); _Documento.AddAuthor("www.bcmWeb.net"); _Documento.AddCreator("www.bcmweb.net"); _Documento.AddKeywords(string.Join(",", docKeywords)); int _PaginaInicioCapitulo = 1; foreach (string _fileName in _pdfFiles) { List <string> _fileSplit = _fileName.Split('_').ToList(); long _IdModulo = long.Parse(_fileSplit.Last().Split('.').First()); tblModulo dataModulo = db.tblModulo.Where(x => x.IdEmpresa == IdEmpresa && x.IdModulo == _IdModulo).FirstOrDefault(); _TableOfContent.Add(new objContenido { Capitulo = dataModulo.Nombre, Indent = false, Page = _PaginaInicioCapitulo }); reader.Add(new PdfReader(_fileName)); i = 0; n = reader[reader.Count - 1].NumberOfPages; while (i < n) { i++; _Documento.SetPageSize(reader[reader.Count - 1].GetPageSizeWithRotation(i)); _Documento.NewPage(); page = _pdfWrite.GetImportedPage(reader[reader.Count - 1], i); PdfContentByte cb = _pdfWrite.DirectContent; rotation = reader[reader.Count - 1].GetPageRotation(i); if (rotation == 90 || rotation == 270) { cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader[reader.Count - 1].GetPageSizeWithRotation(i).Height); } else { cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0); } } _ActualPageWidth = PageSize.LETTER.Width; _PaginaInicioCapitulo += n; } long IdModuloPadre = IdTipoDocumento * 1000000; NombreModulo = db.tblModulo.Where(x => x.IdEmpresa == IdEmpresa && x.IdModulo == IdModuloPadre).FirstOrDefault().Nombre; GenerarIndice(NombreModulo); _Documento.Close(); foreach (PdfReader _reader in reader) { _reader.Close(); _reader.Dispose(); } if (Modulo == eSystemModules.PMI) { MoverDocumentosEscenarios(dataDocumento.Negocios, _CodigoInforme); } _pdfFiles = Directory.GetFiles(_tempFilePath, _pattern, SearchOption.AllDirectories).OrderBy(q => q).ToList(); foreach (string _fileName in _pdfFiles) { File.Delete(_fileName); } } } } catch (Exception ex) { //_Documento.Close(); throw ex; } return(_strDocURL); }
public string split(string ordercode, string pages, string fileid, string userid, string filetype, string username) { string data = pages; JArray jsonarray = JsonConvert.DeserializeObject <JArray>(data); DataTable dt_order = DBMgr.GetDataTable("select * from list_order where code='" + ordercode + "'"); string busiunitcode = dt_order.Rows[0]["busiunitcode"].ToString(); string customercode = dt_order.Rows[0]["customercode"].ToString(); string repunitcode = dt_order.Rows[0]["repunitcode"].ToString(); string busitype = dt_order.Rows[0]["busitype"].ToString(); string tradeway = dt_order.Rows[0]["TRADEWAYCODES"].ToString(); string where = @" where (b.busiunitcode is null or b.busiunitcode='{0}') and (b.customercode is null or b.customercode='{1}') and (b.repunitcode is null or b.repunitcode='{2}') and (b.busitype is null or b.busitype='{3}') and (b.tradeway is null or b.tradeway='{4}')"; string sql_result = @"select filetypeid,filetypename,PROMPT from sys_filetype a inner join config_filesplit b on a.filetypeid=b.filetype " + where; sql_result = string.Format(sql_result, busiunitcode, customercode, repunitcode, busitype, tradeway); DataTable dt_result = DBMgr.GetDataTable(sql_result); if (dt_result.Rows.Count != 0) { for (int i = 0; i < dt_result.Rows.Count; i++) { foreach (JObject jo in jsonarray) { string err_msg = dt_result.Rows[i]["PROMPT"].ToString(); if (jo.Value <string>("c-" + dt_result.Rows[i]["FILETYPEID"] + "@" + dt_result.Rows[i]["FILETYPENAME"]) == "√") { return("error:" + err_msg); } } } } IDatabase db = SeRedis.redis.GetDatabase(); string json = string.Empty; string sql = string.Empty; PdfReader pdfReader; FileInfo fi; DataTable dt; int filepages = 0; db.StringSet(ordercode + ":" + fileid + ":splitdetail", data); sql = "select * from list_attachment where ID='" + fileid + "'"; dt = DBMgr.GetDataTable(sql); //add 强制压缩20180411 string filename = (dt.Rows[0]["FILENAME"] + "").Replace("/", @"\"); string filename_txt = @"d:\ftpserver\" + filename.Replace(".pdf", "").Replace(".PDF", "") + ".txt"; string dir = @"d:\ftpserver\" + filename.Substring(0, filename.LastIndexOf(@"\")); string SearchPattern = filename.Substring(filename.LastIndexOf(@"\") + 1).Replace(".pdf", "").Replace(".PDF", "") + "-web*"; var files = Directory.GetFiles(dir, SearchPattern); if (File.Exists(filename_txt)) { if (files.Length <= 0) { return("{success:false,result:[文件大小为0]}");//没压缩成功 } } fi = new FileInfo(@"D:\ftpserver\" + dt.Rows[0]["FILENAME"]); PdfReader reader_file = new PdfReader(@"D:\ftpserver\" + dt.Rows[0]["FILENAME"]); //2016-6-16压缩改用pdfshrink在后台执行 string compressname = ""; bool bf_iscodecompress = false; //如果pdfshrink压缩文件存在 //if (File.Exists(@"d:\ftpserver\" + (dt.Rows[0]["FILENAME"] + "").Replace(".pdf", "").Replace(".PDF", "") + "-web.pdf")) //{ // compressname = @"d:\ftpserver\" + (dt.Rows[0]["FILENAME"] + "").Replace(".pdf", "").Replace(".PDF", "") + "-web.pdf"; //} if (files.Length > 0) { compressname = files[0]; } else { if (File.Exists(@"d:\Compress\" + fileid + ".pdf"))//如果代码压缩的文件存在 { compressname = @"d:\Compress\" + fileid + ".pdf"; } else { /*fi = new FileInfo(@"D:\ftpserver\" + dt.Rows[0]["FILENAME"]); * CompressPdf(fileid, fi);//不存在则生成压缩文件再进行拆分 * compressname = @"d:\Compress\" + fileid + ".pdf";*/ if (fi.Length / 1024 > reader_file.NumberOfPages * 200)//---文件实际大小 > 计算页数*200K,需要压缩 { bf_iscodecompress = true; CompressPdf(fileid, fi);//不存在则生成压缩文件再进行拆分 } else { fi.CopyTo(@"d:\Compress\" + fileid + ".pdf"); } compressname = @"d:\Compress\" + fileid + ".pdf"; } } if (File.Exists(compressname))//如果压缩文件存在 { try { if (bf_iscodecompress == true && (new FileInfo(@"D:\ftpserver\" + dt.Rows[0]["FILENAME"])).Length / 1024 == (new FileInfo(compressname)).Length / 1024)//压缩文件根源文件大小一样 { //没压缩成功 新增压缩任务 DataTable dt_shrink = new DataTable(); dt_shrink = DBMgr.GetDataTable("select * from pdfshrinklog where attachmentid='" + fileid + "' and ISCOMPRESS=0"); if (dt_shrink.Rows.Count <= 0) { sql = "insert into pdfshrinklog (id,attachmentid) values (pdfshrinklog_id.nextval,'" + fileid + "')"; DBMgr.ExecuteNonQuery(sql); } return("{success:false,result:[压缩文件与源文件大小相同]}");//没压缩成功 } else { pdfReader = new PdfReader(compressname); filepages = pdfReader.NumberOfPages; if (filepages != reader_file.NumberOfPages) { reader_file.Close(); reader_file.Dispose(); pdfReader.Close(); pdfReader.Dispose(); FileInfo di = new FileInfo(compressname); di.Delete(); //File.Delete(compressname); sql = "insert into pdfshrinklog (id,attachmentid) values (pdfshrinklog_id.nextval,'" + fileid + "')"; DBMgr.ExecuteNonQuery(sql); return("{success:false,result:[正在生成源文件正在压缩]}");//没压缩成功 } reader_file.Close(); reader_file.Dispose(); sql = "select * from sys_filetype where parentfiletypeid=" + filetype;//取该文件类型下面所有的子类型 dt = DBMgr.GetDataTable(sql); IList <Int32> pagelist; for (int i = 0; i < dt.Rows.Count; i++) { int rotation = 0; pagelist = new List <Int32>(); foreach (JObject jo in jsonarray) { if (jo.Value <string>("c-" + dt.Rows[i]["FILETYPEID"] + "@" + dt.Rows[i]["FILETYPENAME"]) == "√") { pagelist.Add(jo.Value <Int32>("ID"));//统计出该子类型下面所有的页码 } } if (pagelist.Count > 0) { string new_name = DateTimeToUnixTimestamp(DateTime.Now) + ""; if (!Directory.Exists(@"d:/ftpserver/" + dt.Rows[i]["FILETYPEID"] + @"/" + ordercode)) { Directory.CreateDirectory(@"d:/ftpserver/" + dt.Rows[i]["FILETYPEID"] + @"/" + ordercode); } string newfilename = @"d:/ftpserver/" + dt.Rows[i]["FILETYPEID"] + @"/" + ordercode + @"/" + ordercode + "_" + new_name + ".pdf"; FileStream fs = new FileStream(newfilename, FileMode.Create); Document newDocument = new Document(); PdfWriter pdfWriter = PdfWriter.GetInstance(newDocument, fs); pdfWriter.CloseStream = true; newDocument.Open(); PdfContentByte pdfContentByte = pdfWriter.DirectContent; foreach (Int32 page in pagelist) { newDocument.SetPageSize(pdfReader.GetPageSizeWithRotation(page)); newDocument.NewPage(); PdfImportedPage importedPage = pdfWriter.GetImportedPage(pdfReader, page); rotation = pdfReader.GetPageRotation(page); pdfContentByte.AddTemplate(importedPage, 0, 0); if (rotation == 90 || rotation == 270) { pdfContentByte.AddTemplate(importedPage, 0, -1f, 1f, 0, 0, pdfReader.GetPageSizeWithRotation(page).Height); } else { pdfContentByte.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0); } } fs.Flush(); newDocument.Close(); newDocument.Dispose(); //获取拆分文件的大小 FileInfo info = new FileInfo(newfilename); long infolength = info.Length; decimal filelength = ((decimal)infolength) / 1024 / 1024; string result = filelength.ToString("#0.00"); sql = "insert into LIST_ATTACHMENTDETAIL (id,sourcefilename,filename,attachmentid,filetypeid,splitetime,ordercode,pages,filesize) values (list_attachmentdetail_id.nextval,'{0}','{1}','{2}','{3}',sysdate,'{4}','{5}',{6})"; sql = String.Format(sql, dt.Rows[i]["FILETYPEID"] + @"/" + ordercode + @"/" + ordercode + "_" + new_name + ".pdf", ordercode + "_" + new_name + ".pdf", fileid, dt.Rows[i]["FILETYPEID"], ordercode, string.Join(",", pagelist.ToArray()), result); DBMgr.ExecuteNonQuery(sql); } } pdfReader.Close(); pdfReader.Dispose(); //20170710 判断拆分明细是否存在 DataTable dt_detail_e = new DataTable(); dt_detail_e = DBMgr.GetDataTable("select * from LIST_ATTACHMENTDETAIL where ordercode='" + ordercode + "'"); if (dt_detail_e.Rows.Count > 0) { //拆分完成后更新主文件的状态,同时将拆分好的类型送到页面形成按钮便于查看 sql = "update LIST_ATTACHMENT set SPLITSTATUS=1,CONFIRMSTATUS=1,FILEPAGES=" + filepages + " where id=" + fileid; DBMgr.ExecuteNonQuery(sql); DataTable dt_list_order = DBMgr.GetDataTable("select * from LIST_ORDER where code='" + ordercode + "'"); sql = "update LIST_ORDER set FILESTATUS=1,FILESPLITTIME=sysdate,FILEPAGES=" + filepages + ",FILESPLITEUSERID='" + userid + "',FILESPLITEUSERNAME='******' where code='" + ordercode + "'"; int resultcode = DBMgr.ExecuteNonQuery(sql); if (resultcode > 0) { //若正常拆分在字段修改历史记录表中记录 sql = "insert into list_updatehistory(id,ordercode,type,userid, updatetime, oldfield,newfield,name,fieldname,code,field)" + " values(LIST_UPDATEHISTORY_ID.nextval,'" + ordercode + "','1','" + userid + "',sysdate,'" + dt_list_order.Rows[0]["FILESTATUS"] + "','1','" + username + "','业务—文件状态-WEB','" + ordercode + "','FILESTATUS')"; DBMgr.ExecuteNonQuery(sql); } sql = "select a.id,a.filetypeid,b.filetypename from LIST_ATTACHMENTDETAIL a left join sys_filetype b on a.filetypeid=b.filetypeid where a.ordercode='" + ordercode + "' order by b.sortindex asc"; dt = DBMgr.GetDataTable(sql); json = JsonConvert.SerializeObject(dt); return("{success:true,result:" + json + "}"); } else { return("{success:false,result:[文件记录不存在]}");//拆分明细不存在 } } } catch (Exception ex) { string error = "{\"ordercode\":\"" + ordercode + "\",\"fileid\":\"" + fileid + "\",\"error\":\"" + ex.Message + "\"}"; db.ListRightPush("spliterror", error); return("{success:false,result:[" + error + "]}");//拆分异常 } } else { return("{success:false,result:[压缩文件不存在]}");//压缩文件不存在 } }
protected void Page_Load(object sender, EventArgs e) { string action = Request["action"]; string filetype = Request["filetype"]; string ordercode = Request["ordercode"]; string fileid = Request["fileid"]; string userid = Request["userid"] == "null" ? "" : Request["userid"]; string json = ""; string sql = ""; DataTable dt; PdfReader pdfReader; IDatabase db = SeRedis.redis.GetDatabase(); FileInfo fi; string username = ""; DataTable dt_user = DBMgr.GetDataTable("select * from Sys_User where ID='" + userid + "'"); if (dt_user.Rows.Count > 0) { username = dt_user.Rows[0]["REALNAME"] + ""; } switch (action) { case "merge": string splitfilename = ""; string filestatus = ""; string fileids = Request["fileids"].Replace("[", "").Replace("]", ""); string[] fileidarray = fileids.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); IList <string> pathlist = new List <string>(); //如果传输到这个页面的比如订单文件大于等于两个,需要将这文件合并后再输出 if (fileidarray.Length > 1) { for (int i = 0; i < fileidarray.Length; i++) { sql = "select * from list_attachment where ID=" + fileidarray[i]; dt = DBMgr.GetDataTable(sql); if (dt.Rows.Count > 0) { if (File.Exists(@"d:\ftpserver\" + dt.Rows[0]["FILENAME"] + "")) { pathlist.Add(dt.Rows[0]["FILENAME"] + ""); } } } string orifilename = Guid.NewGuid().ToString(); splitfilename = "/" + DateTime.Now.ToString("yyyy-MM-dd") + "/" + orifilename + ".pdf"; MergePDFFiles(pathlist, @"d:\ftpserver\" + splitfilename); sql = @"insert into list_attachment (id,FILENAME,ORIGINALNAME,UPLOADTIME,FILETYPE,ORDERCODE,FILESUFFIX,uploaduserid,ISUPLOAD) values (list_attachment_id.nextval,'{0}','{1}',sysdate,'{2}','{3}','{4}','{5}','1')"; sql = string.Format(sql, splitfilename, orifilename + ".pdf", 44, ordercode, "pdf", userid); DBMgr.ExecuteNonQuery(sql); //合并完成后数据库删除原有文件,插入新的文件记录"/" + ordercode try { for (int k = 0; k < fileidarray.Length; k++) { sql = "delete from list_attachment where id= '" + fileidarray[k] + "'"; DBMgr.ExecuteNonQuery(sql); } for (int j = 0; j < pathlist.Count; j++) { File.Delete(@"d:\ftpserver\" + pathlist[j]); } } catch (Exception ex) { } } Response.Write("{success:true}"); Response.End(); break; case "loadpdf": sql = "select * from list_attachment where id='" + Request["fileid"] + "'"; dt = DBMgr.GetDataTable(sql); splitfilename = dt.Rows[0]["FILENAME"] + ""; fileid = Request["fileid"]; filestatus = dt.Rows[0]["SPLITSTATUS"] + ""; //0 未拆分 1 已拆分 if (filestatus == "" || filestatus == "0") //如果未拆分,初始化拆分明细界面内容并写入缓存 { //插入待压缩文件的记录【新的压缩方式】 因为工具端上传的文件是没有压缩日志的 sql = "select t.* from pdfshrinklog t where t.attachmentid='" + fileid + "'"; dt = DBMgr.GetDataTable(sql); if (dt.Rows.Count == 0) { sql = "insert into pdfshrinklog (id,attachmentid) values (pdfshrinklog_id.nextval,'" + fileid + "')"; DBMgr.ExecuteNonQuery(sql); } pdfReader = new PdfReader(@"d:\ftpserver\" + splitfilename); int totalPages = pdfReader.NumberOfPages; pdfReader.Close(); pdfReader.Dispose(); sql = "select * from sys_filetype where parentfiletypeid=44 order by sortindex asc"; //取该文件类型下面所有的子类型 dt = DBMgr.GetDataTable(sql); //构建页码表格数据 DataTable dt2 = new DataTable(); DataColumn dc = new DataColumn("ID"); dt2.Columns.Add(dc); for (int k = 0; k < dt.Rows.Count; k++) { dc = new DataColumn("c-" + dt.Rows[k]["FILETYPEID"] + "@" + dt.Rows[k]["FILETYPENAME"]); dt2.Columns.Add(dc); } for (int i = 1; i <= totalPages; i++) { DataRow dr = dt2.NewRow(); dr["ID"] = i; dt2.Rows.Add(dr); } json = JsonConvert.SerializeObject(dt2); //订单文件拆分明细保存至缓存数据库 并设置过期时间是24小时 db.StringSet(ordercode + ":" + fileid + ":splitdetail", json, TimeSpan.FromMinutes(1440)); } else //如果已拆分 直接读取缓存数据库 { if (db.KeyExists(ordercode + ":" + fileid + ":splitdetail")) { json = db.StringGet(ordercode + ":" + fileid + ":splitdetail"); } else { pdfReader = new PdfReader(@"d:\ftpserver\" + splitfilename); int totalPages = pdfReader.NumberOfPages; pdfReader.Close(); pdfReader.Dispose(); sql = "select * from sys_filetype where parentfiletypeid=44 order by sortindex asc"; //取该文件类型下面所有的子类型 dt = DBMgr.GetDataTable(sql); //构建页码表格数据 DataTable dt2 = new DataTable(); DataColumn dc = new DataColumn("ID"); dt2.Columns.Add(dc); for (int k = 0; k < dt.Rows.Count; k++) { dc = new DataColumn("c-" + dt.Rows[k]["FILETYPEID"] + "@" + dt.Rows[k]["FILETYPENAME"]); dt2.Columns.Add(dc); } for (int i = 1; i <= totalPages; i++) { DataRow dr = dt2.NewRow(); dr["ID"] = i; foreach (DataRow tmp in dt.Rows) //一个子类型是一列 取每一列的值 { sql = "select pages from list_attachmentdetail where ordercode='" + ordercode + "' and attachmentid=" + fileid + " and filetypeid=" + tmp["FILETYPEID"]; DataTable sub_dt = DBMgr.GetDataTable(sql); if (sub_dt.Rows.Count > 0) { string[] tmparray = sub_dt.Rows[0]["PAGES"].ToString().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); if (tmparray.Contains <string>(i + "")) { dr["c-" + tmp["FILETYPEID"] + "@" + tmp["FILETYPENAME"]] = "√"; } else { dr["c-" + tmp["FILETYPEID"] + "@" + tmp["FILETYPENAME"]] = ""; } } } dt2.Rows.Add(dr); } json = JsonConvert.SerializeObject(dt2); db.StringSet(ordercode + ":" + fileid + ":splitdetail", json, TimeSpan.FromMinutes(1440)); } } //sql = "select * from sys_filetype where filetypeid=" + filetype; //dt = DBMgr.GetDataTable(sql); //string filetypename = dt.Rows[0]["FILETYPENAME"] + ""; //如果是已经拆分好的 需要调出所有拆分好的文件类型 filetype:'" + filetypename + "' sql = @"select a.id,a.filetypeid,b.filetypename from LIST_ATTACHMENTDETAIL a left join sys_filetype b on a.filetypeid=b.filetypeid where a.attachmentid='" + fileid + "' and a.ordercode='" + ordercode + "' order by b.sortindex asc"; dt = DBMgr.GetDataTable(sql); string json_type = JsonConvert.SerializeObject(dt); Response.Write(@"{success:true,src:'\/file\/" + splitfilename + "',rows:" + json + ",fileid:" + fileid + ",filestatus:'" + filestatus + "',result:" + json_type + "}"); Response.End(); break; case "split": int filepages = 0; string data = Request["pages"]; JArray jsonarray = JsonConvert.DeserializeObject <JArray>(data); db.StringSet(ordercode + ":" + fileid + ":splitdetail", data); sql = "select * from list_attachment where ID='" + fileid + "'"; dt = DBMgr.GetDataTable(sql); //2016-6-16压缩改用pdfshrink在后台执行 string compressname = ""; //如果pdfshrink压缩文件存在 if (File.Exists(@"d:\ftpserver\" + (dt.Rows[0]["FILENAME"] + "").Replace(".pdf", "").Replace(".PDF", "") + "-web.pdf")) { compressname = @"d:\ftpserver\" + (dt.Rows[0]["FILENAME"] + "").Replace(".pdf", "").Replace(".PDF", "") + "-web.pdf"; } else { if (File.Exists(@"d:\Compress\" + fileid + ".pdf")) //如果代码压缩的文件存在 { compressname = @"d:\Compress\" + fileid + ".pdf"; } else { fi = new FileInfo(@"D:\ftpserver\" + dt.Rows[0]["FILENAME"]); CompressPdf(fileid, fi); //不存在则生成压缩文件再进行拆分 compressname = @"d:\Compress\" + fileid + ".pdf"; } } if (File.Exists(compressname)) //如果压缩文件存在 { try { if ((new FileInfo(@"D:\ftpserver\" + dt.Rows[0]["FILENAME"])).Length / 1024 == (new FileInfo(compressname)).Length / 1024) //压缩文件根源文件大小一样 { //没压缩成功 新增压缩任务 DataTable dt_shrink = new DataTable(); dt_shrink = DBMgr.GetDataTable("select * from pdfshrinklog where attachmentid='" + fileid + "' and ISCOMPRESS=0"); if (dt_shrink.Rows.Count <= 0) { sql = "insert into pdfshrinklog (id,attachmentid) values (pdfshrinklog_id.nextval,'" + fileid + "')"; DBMgr.ExecuteNonQuery(sql); } Response.Write("{success:false}"); //没压缩成功 } else { pdfReader = new PdfReader(compressname); filepages = pdfReader.NumberOfPages; sql = "select * from sys_filetype where parentfiletypeid=" + filetype;//取该文件类型下面所有的子类型 dt = DBMgr.GetDataTable(sql); IList <Int32> pagelist; for (int i = 0; i < dt.Rows.Count; i++) { int rotation = 0; pagelist = new List <Int32>(); foreach (JObject jo in jsonarray) { if (jo.Value <string>("c-" + dt.Rows[i]["FILETYPEID"] + "@" + dt.Rows[i]["FILETYPENAME"]) == "√") { pagelist.Add(jo.Value <Int32>("ID")); //统计出该子类型下面所有的页码 } } if (pagelist.Count > 0) { string new_name = DateTimeToUnixTimestamp(DateTime.Now) + ""; if (!Directory.Exists(@"d:/ftpserver/" + dt.Rows[i]["FILETYPEID"] + @"/" + ordercode)) { Directory.CreateDirectory(@"d:/ftpserver/" + dt.Rows[i]["FILETYPEID"] + @"/" + ordercode); } string newfilename = @"d:/ftpserver/" + dt.Rows[i]["FILETYPEID"] + @"/" + ordercode + @"/" + ordercode + "_" + new_name + ".pdf"; FileStream fs = new FileStream(newfilename, FileMode.Create); Document newDocument = new Document(); PdfWriter pdfWriter = PdfWriter.GetInstance(newDocument, fs); pdfWriter.CloseStream = true; newDocument.Open(); PdfContentByte pdfContentByte = pdfWriter.DirectContent; foreach (Int32 page in pagelist) { newDocument.SetPageSize(pdfReader.GetPageSizeWithRotation(page)); newDocument.NewPage(); PdfImportedPage importedPage = pdfWriter.GetImportedPage(pdfReader, page); rotation = pdfReader.GetPageRotation(page); pdfContentByte.AddTemplate(importedPage, 0, 0); if (rotation == 90 || rotation == 270) { pdfContentByte.AddTemplate(importedPage, 0, -1f, 1f, 0, 0, pdfReader.GetPageSizeWithRotation(page).Height); } else { pdfContentByte.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0); } } fs.Flush(); newDocument.Close(); sql = "insert into LIST_ATTACHMENTDETAIL (id,sourcefilename,filename,attachmentid,filetypeid,splitetime,ordercode,pages) values (list_attachmentdetail_id.nextval,'{0}','{1}','{2}','{3}',sysdate,'{4}','{5}')"; sql = String.Format(sql, dt.Rows[i]["FILETYPEID"] + @"/" + ordercode + @"/" + ordercode + "_" + new_name + ".pdf", ordercode + "_" + new_name + ".pdf", fileid, dt.Rows[i]["FILETYPEID"], ordercode, string.Join(",", pagelist.ToArray())); DBMgr.ExecuteNonQuery(sql); } } pdfReader.Close(); pdfReader.Dispose(); //拆分完成后更新主文件的状态,同时将拆分好的类型送到页面形成按钮便于查看 sql = "update LIST_ATTACHMENT set SPLITSTATUS=1,CONFIRMSTATUS=1,FILEPAGES=" + filepages + " where id=" + fileid; DBMgr.ExecuteNonQuery(sql); DataTable dt_list_order = DBMgr.GetDataTable("select * from LIST_ORDER where code='" + ordercode + "'"); sql = "update LIST_ORDER set FILESTATUS=1,FILESPLITTIME=sysdate,FILEPAGES=" + filepages + ",FILESPLITEUSERID='" + userid + "',FILESPLITEUSERNAME='******' where code='" + ordercode + "'"; int resultcode = DBMgr.ExecuteNonQuery(sql); if (resultcode > 0) { //若正常拆分在字段修改历史记录表中记录 sql = "insert into list_updatehistory(id,ordercode,type,userid, updatetime, oldfield,newfield,name,fieldname,code,field)" + " values(LIST_UPDATEHISTORY_ID.nextval,'" + ordercode + "','1','" + userid + "',sysdate,'" + dt_list_order.Rows[0]["FILESTATUS"] + "','1','" + username + "','业务—文件状态-WEB','" + ordercode + "','FILESTATUS')"; DBMgr.ExecuteNonQuery(sql); } sql = "select a.id,a.filetypeid,b.filetypename from LIST_ATTACHMENTDETAIL a left join sys_filetype b on a.filetypeid=b.filetypeid where a.ordercode='" + ordercode + "' order by b.sortindex asc"; dt = DBMgr.GetDataTable(sql); json = JsonConvert.SerializeObject(dt); Response.Write("{success:true,result:" + json + "}"); } } catch (Exception ex) { string error = "{\"ordercode\":\"" + ordercode + "\",\"fileid\":\"" + fileid + "\",\"error\":\"" + ex.Message + "\"}"; db.ListRightPush("spliterror", error); Response.Write("{success:false,result:[" + error + "]}"); //拆分异常 } } else { Response.Write("{success:false}"); //压缩文件不存在 } Response.End(); break; case "cancelsplit": //删除文件明细 string fileids_temp = ""; sql = "select * from list_attachmentdetail where ordercode='" + ordercode + "'"; dt = DBMgr.GetDataTable(sql); for (int i = 0; i < dt.Rows.Count; i++) { if (!fileids_temp.Contains(dt.Rows[i]["attachmentid"].ToString())) { fileids_temp = fileids_temp + dt.Rows[i]["attachmentid"].ToString() + ","; db.KeyDelete(ordercode + ":" + fileid + ":splitdetail"); } if (File.Exists(@"d:/ftpserver/" + dt.Rows[i]["SOURCEFILENAME"])) { File.Delete(@"d:/ftpserver/" + dt.Rows[i]["SOURCEFILENAME"]); } sql = "delete from list_attachmentdetail where id=" + dt.Rows[i]["ID"]; DBMgr.ExecuteNonQuery(sql); } if (fileids_temp != "") { fileids_temp = fileids_temp.Substring(0, fileids_temp.Length - 1); sql = "update LIST_ATTACHMENT set SPLITSTATUS=0 where id in(" + fileids_temp + ")"; DBMgr.ExecuteNonQuery(sql); } DataTable dt_list_order_c = DBMgr.GetDataTable("select * from LIST_ORDER where code='" + ordercode + "'"); //20160922赵艳提出 拆分完,需要更新订单表的 拆分人和时间,和文件状态 sql = "update LIST_ORDER set FILESTATUS=0,FILEPAGES=null,FILESPLITEUSERNAME=null,FILESPLITEUSERID=null,FILESPLITTIME=null where code='" + ordercode + "'"; DBMgr.ExecuteNonQuery(sql); sql = "insert into list_updatehistory(id,ordercode,type,userid, updatetime, oldfield,newfield,name,fieldname,code,field)" + " values(LIST_UPDATEHISTORY_ID.nextval,'" + ordercode + "','1','" + userid + "',sysdate,'" + dt_list_order_c.Rows[0]["FILESTATUS"] + "','0','" + username + "','业务—文件状态-WEB','" + ordercode + "','FILESTATUS')"; DBMgr.ExecuteNonQuery(sql); Response.Write("{success:true}"); Response.End(); break; case "loadfile": sql = "select * from list_attachmentdetail where id='" + fileid + "'"; dt = DBMgr.GetDataTable(sql); if (dt.Rows.Count > 0) { Response.Write(@"{success:true,src:'/file/" + dt.Rows[0]["SOURCEFILENAME"] + "'}"); Response.End(); } break; case "adjustpage": int currentPage = Convert.ToInt32(Request["currentpage"]); string direction = Request["direction"]; sql = "select * from list_attachment where ID=" + fileid; dt = DBMgr.GetDataTable(sql); if (dt.Rows.Count > 0) { if (File.Exists(@"d:\ftpserver\" + dt.Rows[0]["FILENAME"] + "")) { string newid = Guid.NewGuid().ToString(); string outFile = dt.Rows[0]["FILETYPE"] + @"/" + ordercode + @"/" + newid + ".pdf"; AdjustPage(dt.Rows[0]["FILENAME"] + "", currentPage, direction, @"d:/ftpserver/" + outFile); //删除老文件 并更新该记录的FILENAME字段 //2016-8-17测试发现调整页码顺序重新生成文件,删除时有可能文件正在使用中,故原始文件暂不需要删除 下面这句话会报错 //File.Delete(@"d:/ftpserver/" + dt.Rows[0]["FILENAME"]); sql = "update list_attachment set FileName='" + outFile + "',fileguid='" + newid + "',originalname='" + newid + ".pdf' where id=" + fileid; DBMgr.ExecuteNonQuery(sql); Response.Write(@"{success:true,src:'/file/" + outFile + "'}"); Response.End(); } } break; case "compress": string ser_path = Server.MapPath(Request["path"]); fi = new FileInfo(ser_path); CompressPdf(fileid, fi); break; case "loadform": sql = "SELECT * FROM list_order WHERE CODE = '" + ordercode + "'"; dt = DBMgr.GetDataTable(sql); if (!string.IsNullOrEmpty(dt.Rows[0]["ASSOCIATENO"].ToString())) { sql = "SELECT * FROM list_order WHERE CODE != '" + ordercode + "' and ASSOCIATENO='" + dt.Rows[0]["ASSOCIATENO"] + "'"; DataTable dt_gl = DBMgr.GetDataTable(sql); if (dt_gl.Rows.Count > 0) { dt.Rows[0]["ASSOCIATENO"] = dt_gl.Rows[0]["CODE"]; } else { dt.Rows[0]["ASSOCIATENO"] = ""; } } string result = JsonConvert.SerializeObject(dt).Replace("[", "").Replace("]", ""); sql = "select * from list_attachment where ordercode='" + ordercode + "' and filetype=44 order by uploadtime asc"; DataTable dt_file = DBMgr.GetDataTable(sql); string result_file = JsonConvert.SerializeObject(dt_file); Response.Write("{formdata:" + result + ",filedata:" + result_file + "}"); Response.End(); break; case "loadattach": sql = "select * from list_attachment where ordercode='" + ordercode + "' and filetype=44 order by uploadtime asc"; DataTable dt_attach = DBMgr.GetDataTable(sql); string result_attach = JsonConvert.SerializeObject(dt_attach); Response.Write("{filedata:" + result_attach + "}"); Response.End(); break; case "delete": //删除及明细 try { string del_fileids = Request["fileids"].Replace("[", "").Replace("]", ""); string[] del_fileidarray = del_fileids.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < del_fileidarray.Length; i++) { sql = "select * from list_attachment where ID=" + del_fileidarray[i]; dt = DBMgr.GetDataTable(sql); if (dt.Rows.Count > 0) { //删除明细 sql = "select * from list_attachmentdetail where ordercode='" + ordercode + "' and attachmentid=" + del_fileidarray[i]; DataTable dt_detail = DBMgr.GetDataTable(sql); for (int j = 0; j < dt_detail.Rows.Count; j++) { if (File.Exists(@"d:/ftpserver/" + dt_detail.Rows[j]["SOURCEFILENAME"])) { File.Delete(@"d:/ftpserver/" + dt_detail.Rows[j]["SOURCEFILENAME"]); } sql = "delete from list_attachmentdetail where id=" + dt_detail.Rows[j]["ID"]; DBMgr.ExecuteNonQuery(sql); } //删除 if (File.Exists(@"d:/ftpserver/" + dt.Rows[0]["FILENAME"])) { File.Delete(@"d:/ftpserver/" + dt.Rows[0]["FILENAME"]); } sql = "delete from list_attachment where id= '" + del_fileidarray[i] + "'"; DBMgr.ExecuteNonQuery(sql); db.KeyDelete(ordercode + ":" + del_fileidarray[i] + ":splitdetail"); } } sql = "update LIST_ORDER set FILESTATUS=0,FILEPAGES=null,FILESPLITEUSERNAME=null,FILESPLITEUSERID=null,FILESPLITTIME=null where code='" + ordercode + "'"; DBMgr.ExecuteNonQuery(sql); Response.Write("{success:true}"); } catch (Exception ex) { Response.Write("{success:false,error:\"" + ex.Message + "\"}"); } Response.End(); break; } }
/// <summary> /// Merging multiple PDF files in a single one. /// </summary> /// <param name="sourceFiles">List of the source files as byte[]. The first file from the List is the first part form the merged file.</param> /// <returns>Returns the merged file as byte[].</returns> public static byte[] MergePdfFiles(List <byte[]> sourceFiles) { byte[] array; try { int num = 0; PdfReader pdfReader = new PdfReader(sourceFiles[num]); int numberOfPages = pdfReader.NumberOfPages; Document document = new Document(pdfReader.GetPageSizeWithRotation(1)); MemoryStream memoryStream = new MemoryStream(); PdfWriter instance = PdfWriter.GetInstance(document, memoryStream); document.Open(); PdfContentByte directContent = instance.DirectContent; while (num < sourceFiles.Count) { int num1 = 0; while (num1 < numberOfPages) { num1++; document.SetPageSize(pdfReader.GetPageSizeWithRotation(num1)); document.NewPage(); PdfImportedPage importedPage = instance.GetImportedPage(pdfReader, num1); int pageRotation = pdfReader.GetPageRotation(num1); if (pageRotation == 90 || pageRotation == 270) { directContent.AddTemplate(importedPage, 0f, -1f, 1f, 0f, 0f, pdfReader.GetPageSizeWithRotation(num1).Height); } else { directContent.AddTemplate(importedPage, 1f, 0f, 0f, 1f, 0f, 0f); } } num++; if (num >= sourceFiles.Count) { continue; } pdfReader = new PdfReader(sourceFiles[num]); numberOfPages = pdfReader.NumberOfPages; } pdfReader = new PdfReader(sourceFiles[0]); try { document.AddTitle(pdfReader.Info["Title"].ToString()); } catch { } try { document.AddAuthor(pdfReader.Info["Author"].ToString()); } catch { } try { document.AddSubject(pdfReader.Info["Subject"].ToString()); } catch { } try { document.AddKeywords(pdfReader.Info["Keywords"].ToString()); } catch { } try { document.AddCreator(pdfReader.Info["Creator"].ToString()); } catch { } document.Close(); array = memoryStream.ToArray(); } catch { throw; } return(array); }
/// <summary> /// Crea PDF para las Cargas ATM /// </summary> /// <param name="carga">Objeto CargaATM con los datos de la Carga del ATM</param> public void CrearPDFATM() //Abre crear PDF ATM { mostrarDatosCargaATM(); DescargaATM carga = _carga_atm; DateTime hoy = DateTime.Today; string actual = hoy.ToString("dd/MM/yyyy"); string destinopdf = @"\\10.120.131.100\Manifiestos\ATM-" + _carga_atm.Manifiesto + ".pdf"; //DEFINE NOMBRE Y UBICACION DEL PDF QUE SE DESEA CREAR Stream output = new FileStream(destinopdf, FileMode.Create, FileAccess.Write); string plantilla = @"\\10.120.131.100\Releases\manifiesto5.pdf"; //DEFINE LA UBICACION Y EL NOMBRE DE LA PLANTILLA A USAR PdfReader readerBicycle = null; Document documento = new Document(); FileStream theFile = new FileStream(plantilla, FileMode.Open, FileAccess.Read); PdfWriter writer = PdfWriter.GetInstance(documento, output); documento.Open(); readerBicycle = new PdfReader(theFile); PdfTemplate background = writer.GetImportedPage(readerBicycle, 1); documento.NewPage(); iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(@"\\10.120.9.20\Blindados\Firmas\atencionsucursales-tripulacion1352-colaboradorrecibe228-colaboradorentrega135-fecha20140715.jpg"); //iTextSharp.text.Image.GetInstance(@"\\10.120.9.20\Blindados\Firmas\atencionsucursales-tripulacion"+carga.Carga.Tripulacion.ID.ToString()+ //"-colaboradorrecibe"+carga.Carga.Tripulacion.Portavalor.ID.ToString()+"-colaboradorentrega135-fecha"+carga.Fecha.Year.ToString()+carga.Fecha.Month.ToString()+carga.Fecha.Day.ToString()+".jpg"); iTextSharp.text.Image pic2 = iTextSharp.text.Image.GetInstance(@"\\10.120.9.20\Blindados\Firmas\atencionsucursales-tripulacion1352-colaboradorrecibe228-colaboradorentrega135-fecha20140715.jpg"); iTextSharp.text.Image pic3 = iTextSharp.text.Image.GetInstance(@"\\10.120.9.20\Blindados\Firmas\atencionsucursales-tripulacion1352-colaboradorrecibe228-colaboradorentrega135-fecha20140715.jpg"); //pic.RotationDegrees = 90; //pic2.RotationDegrees = 90; //pic3.RotationDegrees = 90; _pcb = writer.DirectContentUnder; _pcb.AddTemplate(background, 0, 0); _pcb = writer.DirectContent; _pcb.BeginText(); pic.ScaleAbsolute(75, 45); pic.SetAbsolutePosition(440, 462); documento.Add(pic); pic2.ScaleAbsolute(75, 45); pic2.SetAbsolutePosition(442, 357); documento.Add(pic2); pic3.ScaleAbsolute(75, 35); pic3.SetAbsolutePosition(442, 157); documento.Add(pic3); //pic.ScaleAbsolute(25, 20); //pic.SetAbsolutePosition(500, 384); //documento.Add(pic); SetFontBarCode(8); //ESTABLECE LA FUENTE E IMPRIME CON LA FUENTE BARCODE HASTA SER CAMBIADA PrintText("*" + carga.Manifiesto.Codigo + "*", 335, 561); //Imprime codigo de barras SetFont(6); PrintText("No: ATM-" + carga.Manifiesto.Codigo, 335, 545); //Imprime numero de manifiesto SetFont(8); //CAMBIAMOS LA FUENTE montoLetrasPdf(montoenletras); //Imprime monto total en letras y valida el tamaño PrintText(_tipocambio.Venta.ToString("N2"), 311, 525); //Imprime tipo de cambio PrintText(carga.Cartuchos.Count.ToString(), 360, 525); //Cantidad depositos PrintText("1", 440, 517); //Imprime cantidad de manifiestos //LADO IZQUIERDO PrintText("ATM", 90, 490); //Origen de los fondos PrintText("BAC San José", 184, 60); //Recibido de PrintText("Centro de Dist. Cipreses", 59, 465); //Direccion PrintText("CURRIDABAT", 44, 416); //Ciudad PrintText("SAN JOSE", 175, 417); //Provincia PrintText(carga.Carga.Cajero.ToString(), 19, 384); //Nombre de Persona que preparó cargamento PrintText(carga.Carga.Fecha_asignada.ToShortDateString(), 230, 384); //Fecha de Entrega if (carga.Carga.Tripulacion != null) { PrintText(carga.Carga.Tripulacion.Portavalor.ToString(), 52, 354); //Entregado a } else { PrintText("", 52, 354); } PrintText(carga.ATM.Oficinas, 223, 354); //Oficinas PrintText("Centro de Dist. Cipreses", 45, 330); //Direccion PrintText("CURRIDABAT", 46, 306); //CIUDAD PrintText("SAN JOSE", 178, 307); //Provincia //MARCHAMOS BT BULTOS Y MONTO PrintText(carga.Carga.Manifiesto.Codigo, 362, 77); //Provincia //int bultos = 0; //if (carga.Cartuchos.Count > 5) //{ int fila = 155; if (carga.Carga.Monto_asignado_colones > 0) { PrintText(("CRC " + carga.Carga.Monto_asignado_colones.ToString("N2")), 148, fila); /*MONTO colones*/ PrintText("1", 86, fila); /*BULTOS*/ PrintText("B", 110, fila); /*BT*/ PrintText(carga.Manifiesto.Marchamo, 20, fila); /*BT*/ fila = fila - 20; } if (carga.Carga.Monto_asignado_dolares > 0) { PrintText(("USD " + carga.Carga.Monto_asignado_dolares.ToString("N2")), 246, fila); /*MONTO dolares*/ PrintText("1", 111, fila); /*BULTOS*/ PrintText("B", 85, fila); /*BT*/ PrintText(carga.Manifiesto.Marchamo, 20, fila); /*BT*/ fila = fila - 20; } if (carga.Carga.Monto_asignado_euros > 0) { PrintText(("EUR " + carga.Carga.Monto_asignado_euros.ToString("N2")), fila, 226); /*MONTO Euros*/ PrintText("1", 114, fila); /*BULTOS*/ PrintText("B", 85, fila); /*BT*/ PrintText(carga.Manifiesto.Marchamo, 20, fila); /*BT*/ } PrintText(lblGranTotal.Text, 149, 35); //LADO DERECHO if (carga.Carga.Tripulacion != null) { PrintText(carga.Carga.ColaboradorRecibidoBoveda.ToString(), 303, 486); //Nombre portavalor recibe } else { PrintText("", 303, 486); //Nombre portavalor recibe } PrintText(carga.Carga.Ruta.ToString(), 361, 460); //Ruta PrintText(lblcantBultos.Text, 311, 460); PrintText(carga.Carga.Hora_Llegada.ToShortTimeString(), 305, 411); PrintText(carga.Carga.Hora_Salida.ToShortTimeString(), 358, 411); PrintText(carga.Carga.Fecha_asignada.ToShortDateString(), 333, 437); //Fecha PrintText(lblPortavalorRuta.Text, 306, 375); //Responsable Ruta PrintText(carga.ATM.Numero.ToString(), 304, 350); //Numero de ATM if (carga.ATM.Full) { PrintText("X", 365, 325); // x de normal } else { PrintText("X", 306, 325); //x de full } PrintText(("CRC " + carga.Monto_descarga_colones.ToString("N2")), 311, 312); //monto descarga colones PrintText(("USD " + carga.Monto_descarga_dolares.ToString("N2")), 318, 300); //monto descarga dolares PrintText(carga.Manifiesto.Bolsa_rechazo, 313, 252); //Numero de marchamo de rechazo PrintText(lblComentario.Text, 311, 230); if (carga.ATM.Full) { PrintText(carga.Carga.Manifiesto_full.Marchamo, 379, 499); //monto descarga dolares } else { PrintText(carga.Manifiesto.Marchamo_adicional, 379, 499);// marchamo adicional } _pcb.EndText(); writer.Flush(); if (readerBicycle == null) { readerBicycle.Close(); } documento.Close(); } //Cierra crear PDF ATM
private ActionResult AddBackgroundToPdf(string sourceFilename, string destinationFilename, IJob job) { Logger.Trace("Start adding Background to " + sourceFilename); var pdfReader = new PdfReader(sourceFilename); int nFile = pdfReader.NumberOfPages; var backgroundPdfReader = new PdfReader(job.Profile.BackgroundPage.File); Logger.Debug("BackgroundFile: " + Path.GetFullPath(job.Profile.BackgroundPage.File)); int nBackground = backgroundPdfReader.NumberOfPages; int startOffset; //number of front pages without background try { startOffset = StartOffsetAccordingToCover(job.Profile); } catch (Exception ex) { Logger.Error("Excpetion while detecting number of pages of the cover file: " + job.Profile.AttachmentPage.File + "\r\n" + ex); return(new ActionResult(ActionId, 105)); } int endPage; //last page with background try { endPage = nFile - EndOffsetAccordingToAttachment(job.Profile); } catch (Exception ex) { Logger.Error("Excpetion while detecting number of pages of the attachment file: " + job.Profile.AttachmentPage.File + "\r\n" + ex); return(new ActionResult(ActionId, 106)); } var stream = new FileStream(destinationFilename, FileMode.Create, FileAccess.Write); var stamper = new PdfStamper(pdfReader, stream); for (int i = 1; i <= nFile; i++) { int backgroundPage = GetBackgroundPageNumber(i, nBackground, job.Profile.BackgroundPage.Repeat, startOffset, endPage); if (backgroundPage < 1) { continue; } PdfImportedPage page = stamper.GetImportedPage(backgroundPdfReader, backgroundPage); PdfContentByte background = stamper.GetUnderContent(i); Rectangle wmsize = backgroundPdfReader.GetPageSize(backgroundPage); Rectangle pdfsize = pdfReader.GetPageSize(i); if ((pdfReader.GetPageRotation(i) == 90) || (pdfReader.GetPageRotation(i) == 270)) { background.AddTemplate(page, 0, -1f, 1f, 0, ((pdfsize.Height - wmsize.Height) / 2), wmsize.Width + (pdfsize.Width - wmsize.Width) / 2); //270° Logger.Debug("BackgroundPage " + backgroundPage + " turned right, because of automatic rotation of page " + i); } else if ((pdfsize.Height < pdfsize.Width) && (wmsize.Height > wmsize.Width)) { //pdfsize.height and width must be changed for this calculation, because the page was rotated background.AddTemplate(page, 0, -1f, 1f, 0, (pdfsize.Width - wmsize.Height) / 2, wmsize.Width + ((pdfsize.Height - wmsize.Width) / 2)); //270° Logger.Debug("BackgroundPage " + backgroundPage + " turned right to fit better in page " + i); } else { background.AddTemplate(page, (pdfsize.Width - wmsize.Width) / 2, (pdfsize.Height - wmsize.Height) / 2); } //0° } // cos sin -sin cos dx dy //background.AddTemplate(page, 0, 1f, -1f, 0, 0, 0 ); //90° //background.AddTemplate(page, -1f, 0, 0, -1f, 0, 0 ); //180° //background.AddTemplate(page, 0, -1f, 1f, 0, 0, 0 ); //270° //background.AddTemplate(page, 1f, 0, 0, 1f, 0, 0 ); //0° stamper.Close(); return(new ActionResult()); }
public string PrintMergedFile(List <string> files, string pdfPath) { try { if (!Directory.Exists(pdfPath)) { Directory.CreateDirectory(pdfPath); } string mergedFileName = "MergedFiles.pdf"; string mergedPath = pdfPath + "\\" + mergedFileName; Document document = new Document(); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(mergedPath, FileMode.Create)); document.Open(); PdfContentByte cb = writer.DirectContent; PdfImportedPage page; int n = 0; int rotation = 0; foreach (string filename in files) { PdfReader reader = new PdfReader(pdfPath + filename); n = reader.NumberOfPages; int i = 0; while (i < n) { i++; document.SetPageSize(reader.GetPageSizeWithRotation(1)); document.NewPage(); if (i == 1) { Chunk fileRef = new Chunk(" "); fileRef.SetLocalDestination(pdfPath + filename); document.Add(fileRef); } page = writer.GetImportedPage(reader, i); rotation = reader.GetPageRotation(i); if (rotation == 90 || rotation == 270) { cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height); } else { cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); } } } document.Close(); return(mergedFileName); } catch (Exception ex) { throw ex; } }
/* will print A4 Portrait 8.27 x 11.69 */ protected void print_A4_portrait() { 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"); //if (!File.Exists(fileOUT)) //{ // File.Create(fileOUT).Dispose(); //} FileStream fs = new FileStream(fileOUT, FileMode.Create); fs.Write(bytes, 0, bytes.Length); fs.Close(); Document document = new Document(PageSize.A4); //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 byte[] CreatePdf() { using (MemoryStream ms = new MemoryStream()) { // step 1 using (Document document = new Document(new Rectangle(850, 600))) { // step 2 PdfWriter writer = PdfWriter.GetInstance(document, ms); // step 3 document.Open(); // step 4 PdfContentByte canvas = writer.DirectContent; // add the clipped image Image img = Image.GetInstance( Path.Combine(Utility.ResourceImage, RESOURCE) ); float w = img.ScaledWidth; float h = img.ScaledHeight; canvas.Ellipse(1, 1, 848, 598); canvas.Clip(); canvas.NewPath(); canvas.AddImage(img, w, 0, 0, h, 0, -600); // Create a transparent PdfTemplate PdfTemplate t2 = writer.DirectContent.CreateTemplate(850, 600); PdfTransparencyGroup transGroup = new PdfTransparencyGroup(); transGroup.Put(PdfName.CS, PdfName.DEVICEGRAY); transGroup.Isolated = true; transGroup.Knockout = false; t2.Group = transGroup; // Add transparent ellipses to the template int gradationStep = 30; float[] gradationRatioList = new float[gradationStep]; for (int i = 0; i < gradationStep; i++) { /* * gotta love .NET, guess they forgot to copy java.lang.Math.toRadians */ double radians = (Math.PI / 180) * 90.0f / gradationStep * (i + 1); gradationRatioList[i] = 1 - (float)Math.Sin(radians); } for (int i = 1; i < gradationStep + 1; i++) { t2.SetLineWidth(5 * (gradationStep + 1 - i)); t2.SetGrayStroke(gradationRatioList[gradationStep - i]); t2.Ellipse(0, 0, 850, 600); t2.Stroke(); } // Create an image mask for the direct content PdfDictionary maskDict = new PdfDictionary(); maskDict.Put(PdfName.TYPE, PdfName.MASK); maskDict.Put(PdfName.S, new PdfName("Luminosity")); maskDict.Put(new PdfName("G"), t2.IndirectReference); PdfGState gState = new PdfGState(); gState.Put(PdfName.SMASK, maskDict); canvas.SetGState(gState); canvas.AddTemplate(t2, 0, 0); } return(ms.ToArray()); } }
public override void OnEndPage(PdfWriter writer, Document document) { base.OnEndPage(writer, document); if (npages.juststartednewset) { EndPageSet(); } string text; float len; //---Header left text = HeadText; const float HeadFontSize = 11f; len = font.GetWidthPoint(text, HeadFontSize); dc.BeginText(); dc.SetFontAndSize(font, HeadFontSize); dc.SetTextMatrix(30, document.PageSize.Height - 30); dc.ShowText(text); dc.EndText(); dc.BeginText(); dc.SetFontAndSize(font, HeadFontSize); dc.SetTextMatrix(30, document.PageSize.Height - 30 - (HeadFontSize * 1.5f)); dc.ShowText(HeadText2); dc.EndText(); //---Barcode right var bc = new Barcode39(); bc.Font = null; bc.Code = Barcode; bc.X = 1.2f; var img = bc.CreateImageWithBarcode(dc, null, null); var h = font.GetAscentPoint(text, HeadFontSize); img.SetAbsolutePosition(document.PageSize.Width - img.Width - 30, document.PageSize.Height - 30 - img.Height + h); dc.AddImage(img); //---Column 1 text = "Page " + (pg) + " of "; len = font.GetWidthPoint(text, 8); dc.BeginText(); dc.SetFontAndSize(font, 8); dc.SetTextMatrix(30, 30); dc.ShowText(text); dc.EndText(); dc.AddTemplate(npages.template, 30 + len, 30); npages.n = pg++; //---Column 2 text = "Attendance Rollsheet"; len = font.GetWidthPoint(text, 8); dc.BeginText(); dc.SetFontAndSize(font, 8); dc.SetTextMatrix(document.PageSize.Width / 2 - len / 2, 30); dc.ShowText(text); dc.EndText(); //---Column 3 text = Util.Now.ToShortDateString(); len = font.GetWidthPoint(text, 8); dc.BeginText(); dc.SetFontAndSize(font, 8); dc.SetTextMatrix(document.PageSize.Width - 30 - len, 30); dc.ShowText(text); dc.EndText(); }
public void OnEndPage(PdfWriter writer, Document document) { base.OnEndPage(writer, document); Font baseFontNormal = new Font(Font.FontFamily.HELVETICA, 12f, Font.BOLD, new BaseColor(17, 130, 255)); Font baseFontBig = new Font(Font.FontFamily.HELVETICA, 8f, Font.BOLD, BaseColor.BLACK); Phrase p1Header = new Phrase("Jéssyka ● Lucena", baseFontNormal); //Create PdfTable object PdfPTable pdfTab = new PdfPTable(3); //We will have to create separate cells to include image logo and 2 separate strings //Row 1 PdfPCell pdfCell1 = new PdfPCell(); PdfPCell pdfCell2 = new PdfPCell(p1Header); PdfPCell pdfCell3 = new PdfPCell(); String text = writer.PageNumber.ToString(); //Add paging to header /* { * cb.BeginText(); * cb.SetFontAndSize(bf, 12); * cb.SetTextMatrix(document.PageSize.GetRight(50), document.PageSize.GetTop(45)); * cb.ShowText(text); * cb.EndText(); * float len = bf.GetWidthPoint(text, 12); * //Adds "12" in Page 1 of 12 * cb.AddTemplate(headerTemplate, document.PageSize.GetRight(50) + len, document.PageSize.GetTop(45)); * }*/ //Add paging to footer { cb.BeginText(); cb.SetFontAndSize(bf, 12); cb.SetTextMatrix(document.PageSize.GetRight(50), document.PageSize.GetBottom(30)); cb.ShowText(text); cb.EndText(); float len = bf.GetWidthPoint(text, 12); cb.AddTemplate(footerTemplate, document.PageSize.GetRight(50) + len, document.PageSize.GetBottom(30)); } //Row 2 PdfPCell pdfCell4 = new PdfPCell(new Phrase("FISIOTERAPEUTA", baseFontBig)); PdfPCell pdfCell41 = new PdfPCell(new Phrase("CRF 248649-F", baseFontBig)); //Row 3 PdfPCell pdfCell5 = new PdfPCell(new Phrase("Data: " + PrintTime.ToShortDateString(), baseFontBig)); PdfPCell pdfCell6 = new PdfPCell(); PdfPCell pdfCell7 = new PdfPCell(new Phrase("Hora: " + string.Format("{0:t}", DateTime.Now), baseFontBig)); //set the alignment of all three cells and set border to 0 pdfCell1.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell3.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell4.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell41.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell5.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell6.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell7.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell2.VerticalAlignment = Element.ALIGN_BOTTOM; pdfCell3.VerticalAlignment = Element.ALIGN_MIDDLE; pdfCell4.VerticalAlignment = Element.ALIGN_TOP; pdfCell41.VerticalAlignment = Element.ALIGN_TOP; pdfCell5.VerticalAlignment = Element.ALIGN_MIDDLE; pdfCell6.VerticalAlignment = Element.ALIGN_MIDDLE; pdfCell7.VerticalAlignment = Element.ALIGN_MIDDLE; pdfCell4.Colspan = 3; pdfCell41.Colspan = 3; pdfCell1.Border = 0; pdfCell2.Border = 0; pdfCell3.Border = 0; pdfCell4.Border = 0; pdfCell41.Border = 0; pdfCell5.Border = 0; pdfCell6.Border = 0; pdfCell7.Border = 0; //add all three cells into PdfTable pdfTab.AddCell(pdfCell1); pdfTab.AddCell(pdfCell2); pdfTab.AddCell(pdfCell3); pdfTab.AddCell(pdfCell4); pdfTab.AddCell(pdfCell41); pdfTab.AddCell(pdfCell5); pdfTab.AddCell(pdfCell6); pdfTab.AddCell(pdfCell7); pdfTab.TotalWidth = document.PageSize.Width - 80f; pdfTab.WidthPercentage = 70; //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable //first param is start row. -1 indicates there is no end row and all the rows to be included to write //Third and fourth param is x and y position to start writing pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent); //Move the pointer and draw line to separate header section from rest of page cb.MoveTo(40, document.PageSize.Height - 100); cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100); cb.Stroke(); //Move the pointer and draw line to separate footer section from rest of page cb.MoveTo(40, document.PageSize.GetBottom(50)); cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50)); cb.Stroke(); }
public override void OnEndPage(PdfWriter writer, Document document) { base.OnEndPage(writer, document); Font baseFontNormal = new Font(Font.FontFamily.HELVETICA, 12f, Font.NORMAL, BaseColor.BLACK); Font baseFontBig = new Font(Font.FontFamily.HELVETICA, 12f, Font.BOLD, BaseColor.BLACK); Phrase p1Header = new Phrase("Orçamento " + data, baseFontNormal); //Create PdfTable object PdfPTable pdfTab = new PdfPTable(3); Image i = Image.GetInstance(new Uri(Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData) + "\\SGEA\\LogoPrograma.png")); i.ScaleAbsolute(64, 64); //We will have to create separate cells to include image logo and 2 separate strings //Row 1 PdfPCell pdfCell1 = new PdfPCell(i); PdfPCell pdfCell2 = new PdfPCell(); PdfPCell pdfCell3 = new PdfPCell(p1Header); string text = "Página " + writer.PageNumber + " de "; cb.BeginText(); cb.SetFontAndSize(bf, 12); cb.SetTextMatrix(document.PageSize.GetRight(180), document.PageSize.GetBottom(30)); cb.ShowText(text); cb.EndText(); float len = bf.GetWidthPoint(text, 12); cb.AddTemplate(footerTemplate, document.PageSize.GetRight(180) + len, document.PageSize.GetBottom(30)); pdfCell1.HorizontalAlignment = Element.ALIGN_LEFT; pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell3.HorizontalAlignment = Element.ALIGN_RIGHT; pdfCell2.VerticalAlignment = Element.ALIGN_TOP; pdfCell3.VerticalAlignment = Element.ALIGN_TOP; pdfCell1.Border = 0; pdfCell2.Border = 0; pdfCell3.Border = 0; //add all three cells into PdfTable pdfTab.AddCell(pdfCell1); pdfTab.AddCell(pdfCell2); pdfTab.AddCell(pdfCell3); pdfTab.TotalWidth = document.PageSize.Width - 80f; pdfTab.WidthPercentage = 70; //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable //first param is start row. -1 indicates there is no end row and all the rows to be included to write //Third and fourth param is x and y position to start writing pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent); //Move the pointer and draw line to separate header section from rest of page cb.MoveTo(40, document.PageSize.Height - 100); cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100); cb.Stroke(); //Move the pointer and draw line to separate footer section from rest of page cb.MoveTo(40, document.PageSize.GetBottom(50)); cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50)); cb.Stroke(); }
public static string AddCommentsToFile(string fileName, string outfilepath, string userComments, PdfPTable newTable) { string outputFileName = outfilepath; //Step 1: Create a Docuement-Object Document document = new Document(); try { //Step 2: we create a writer that listens to the document PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outputFileName, FileMode.Create)); //Step 3: Open the document document.Open(); PdfContentByte cb = writer.DirectContent; //The current file path string filename = fileName; // we create a reader for the document PdfReader reader = new PdfReader(filename); for (int pageNumber = 1; pageNumber < reader.NumberOfPages + 1; pageNumber++) { document.SetPageSize(reader.GetPageSizeWithRotation(1)); document.NewPage(); //Insert to Destination on the first page if (pageNumber == 1) { Chunk fileRef = new Chunk(" "); fileRef.SetLocalDestination(filename); document.Add(fileRef); } PdfImportedPage page = writer.GetImportedPage(reader, pageNumber); int rotation = reader.GetPageRotation(pageNumber); if (rotation == 90 || rotation == 270) { cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(pageNumber).Height); } else { cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); } } // Add a new page to the pdf file document.NewPage(); Paragraph paragraph = new Paragraph(); Font titleFont = new Font(iTextSharp.text.Font.HELVETICA , 15 , iTextSharp.text.Font.BOLD , Color.BLACK ); Chunk titleChunk = new Chunk("Comments", titleFont); paragraph.Add(titleChunk); document.Add(paragraph); paragraph = new Paragraph(); Font textFont = new Font(iTextSharp.text.Font.HELVETICA , 12 , iTextSharp.text.Font.NORMAL , Color.BLACK ); Chunk textChunk = new Chunk(userComments, textFont); paragraph.Add(textChunk); document.Add(paragraph); document.Add(newTable); } catch (Exception e) { throw e; } finally { document.Close(); } return(outputFileName); }
protected void btn_Pdf_Vat_Click(object sender, EventArgs e) { iTextSharp.text.Font font2 = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8f, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.UNDERLINE, iTextSharp.text.BaseColor.RED); Response.ContentType = "application/pdf"; string FileName = "Vat" + DateTime.Now + ".pdf"; Response.AddHeader("content-disposition", "attachment;filename=" + FileName); Response.Cache.SetCacheability(HttpCacheability.NoCache); data_grid.Columns[1].Visible = false; data_grid.Columns[0].Visible = false; data_grid.Columns[2].Visible = false; StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); data_grid.RenderControl(hw); DataTable dt1 = new DataTable(); dt1 = (DataTable)Session["data_grid"]; Boolean columnExists = dt1.Columns.Contains("Filename"); Boolean columnPageno = dt1.Columns.Contains("PageNo"); if (!columnPageno) { dt1.Columns.Add("PageNo"); } Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f); var writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); pdfDoc.NewPage(); List <string> ImageVatStr = GetPdfImagesInVatHTMLString(sw.ToString()); var unique_payments_Expense = new HashSet <string>(ImageVatStr); int startOfImages = GetLastPageNoExpenseTableInPdf(dt1); Dictionary <int, string> dict = new Dictionary <int, string>(); dict = ReturnDictionary(startOfImages, unique_payments_Expense); for (int rows = 0; rows < dt1.Rows.Count; rows++) { for (int count1 = 0; count1 < dict.Count; count1++) { var element = dict.ElementAt(count1); var Key = element.Key; var Value = element.Value; if (dt1.Rows[rows]["VatFileName"].ToString() == Value) { dt1.Rows[rows]["PageNo"] = Key; } } } PdfPTable PdfTable1 = new PdfPTable(dt1.Columns.Count - 4); PdfTable1.WidthPercentage = 100f; int pageno = 0; if (dt1 != null) { PdfPCell PdfPCell = null; iTextSharp.text.Font font = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLUE); PdfPCell = new PdfPCell(new Phrase(new Chunk("Date", font))); PdfTable1.AddCell(PdfPCell); PdfPCell = new PdfPCell(new Phrase(new Chunk("AmountPaid", font))); PdfTable1.AddCell(PdfPCell); PdfPCell = new PdfPCell(new Phrase(new Chunk("Payment", font))); PdfTable1.AddCell(PdfPCell); PdfPCell = new PdfPCell(new Phrase(new Chunk("Description", font))); PdfTable1.AddCell(PdfPCell); PdfPCell = new PdfPCell(new Phrase(new Chunk("Comments", font))); PdfTable1.AddCell(PdfPCell); PdfPCell = new PdfPCell(new Phrase(new Chunk("Item", font))); PdfTable1.AddCell(PdfPCell); PdfPCell = new PdfPCell(new Phrase(new Chunk("VatAmount", font))); PdfTable1.AddCell(PdfPCell); PdfPCell = new PdfPCell(new Phrase(new Chunk("VatReceipt", font))); PdfTable1.AddCell(PdfPCell); PdfPCell = new PdfPCell(new Phrase(new Chunk("PageNo", font))); PdfTable1.AddCell(PdfPCell); //How add the data from datatable to pdf table iTextSharp.text.Font font1 = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); for (int rows = 0; rows < dt1.Rows.Count; rows++) { for (int column = 0; column < dt1.Columns.Count; column++) { if (column == 10) { //Chunk chunk = new Chunk(dt1.Rows[rows]["Filename"].ToString(), font2); Chunk chunk = new Chunk("View", font2); var des = new PdfDestination(PdfDestination.XYZ, 0, pdfDoc.PageSize.Height, 0.99f); pageno = int.Parse(dt1.Rows[rows]["PageNo"].ToString()); PdfAction action = PdfAction.GotoLocalPage(pageno, des, writer); chunk.SetAction(action); PdfPCell = new PdfPCell(new Paragraph(chunk)); PdfTable1.AddCell(PdfPCell); } else { if (column == 0 || column == 6 || column == 7 || column == 11) { } else { PdfPCell = new PdfPCell(new Paragraph(new Chunk(dt1.Rows[rows][column].ToString(), font1))); PdfTable1.AddCell(PdfPCell); } } } } PdfTable1.SpacingBefore = 15f; // Give some space after the text or it may overlap the table } //Add WaterMark string watermarkText = "10bitsSolutions"; float fontSize = 80; float xPosition = 300; float yPosition = 400; float angle = 45; try { PdfContentByte under = writer.DirectContentUnder; BaseFont baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); under.BeginText(); under.SetColorFill(iTextSharp.text.pdf.CMYKColor.LIGHT_GRAY); under.SetFontAndSize(baseFont, fontSize); under.ShowTextAligned(PdfContentByte.ALIGN_CENTER, watermarkText, xPosition, yPosition, angle); under.EndText(); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } //End Water mark pdfDoc.Add(PdfTable1); PdfImportedPage page = null; PdfContentByte cb = writer.DirectContent; foreach (string s in unique_payments_Expense) { PdfReader pdfReader = new PdfReader(s); int numberOfPages = pdfReader.NumberOfPages; for (int i = 1; i <= numberOfPages; i++) { page = writer.GetImportedPage(pdfReader, i); pdfDoc.NewPage(); cb.AddTemplate(page, 5, 5); Chunk a = new Chunk("Top", font2); a.SetAction(new PdfAction(PdfAction.FIRSTPAGE)); pdfDoc.Add(a); } } dt1.Columns.Remove("PageNo"); Session["data_grid"] = dt1; pdfDoc.Close(); Response.Write(pdfDoc); Response.End(); }
protected void btnCreateExampleInvoice_Click(object sender, EventArgs e) { try { // Read the sample XML file using the contructor, giving the file path Invoice invoice = new Invoice(Server.MapPath("invoices") + "\\invoice_123456.xml"); // Create references for each of the on-row tables to make it easier to access the values // in the table using syntax like this: drHead["invoiceId"].ToString() DataRow drHead = invoice.GetInvoiceHeader().Rows[0]; DataRow drTotal = invoice.GetInvoiceTotal().Rows[0]; DataRow drPayee = invoice.GetInvoicePayeeInfo().Rows[0]; using (System.IO.FileStream fs = new FileStream(Server.MapPath("invoices") + "\\" + "Invoice_" + drHead["invoiceId"].ToString() + ".pdf", FileMode.Create)) { Document document = new Document(PageSize.A4, 25, 25, 30, 1); PdfWriter writer = PdfWriter.GetInstance(document, fs); // Add meta information to the document document.AddAuthor("Mikael Blomquist"); document.AddCreator("Sample application using iTestSharp"); document.AddKeywords("PDF tutorial education"); document.AddSubject("Describing the steps creating a PDF document"); document.AddTitle("PDF creation using iTextSharp - Sample invoice"); // Open the document to enable you to write to the document document.Open(); // Makes it possible to add text to a specific place in the document using // a X & Y placement syntax. PdfContentByte cb = writer.DirectContent; // Add a footer template to the document cb.AddTemplate(PdfFooter(cb, drPayee), 30, 1); // Add a logo to the invoice iTextSharp.text.Image png = iTextSharp.text.Image.GetInstance(Server.MapPath("mbase_emc2.png")); png.ScaleAbsolute(200, 55); png.SetAbsolutePosition(40, 750); cb.AddImage(png); // First we must activate writing cb.BeginText(); // First we write out the header information // Start with the invoice type header writeText(cb, drHead["invoiceType"].ToString(), 350, 820, f_cb, 14); // HEader details; invoice number, invoice date, due date and customer Id writeText(cb, "Invoice No", 350, 800, f_cb, 10); writeText(cb, drHead["invoiceId"].ToString(), 420, 800, f_cn, 10); writeText(cb, "Invoice date", 350, 788, f_cb, 10); writeText(cb, drHead["invoiceDate"].ToString(), 420, 788, f_cn, 10); writeText(cb, "Due date", 350, 776, f_cb, 10); writeText(cb, drHead["dueDate"].ToString(), 420, 776, f_cn, 10); writeText(cb, "Customer", 350, 764, f_cb, 10); writeText(cb, drHead["customerId"].ToString(), 420, 764, f_cn, 10); // Delivery address details int left_margin = 40; int top_margin = 720; writeText(cb, "Delivery address", left_margin, top_margin, f_cb, 10); writeText(cb, drHead["delCustomerName"].ToString(), left_margin, top_margin - 12, f_cn, 10); writeText(cb, drHead["delAddress1"].ToString(), left_margin, top_margin - 24, f_cn, 10); writeText(cb, drHead["delAddress2"].ToString(), left_margin, top_margin - 36, f_cn, 10); writeText(cb, drHead["delAddress3"].ToString(), left_margin, top_margin - 48, f_cn, 10); writeText(cb, drHead["delZipcode"].ToString(), left_margin, top_margin - 60, f_cn, 10); writeText(cb, drHead["delCity"].ToString() + ", " + drHead["delCountry"].ToString(), left_margin + 65, top_margin - 60, f_cn, 10); // Invoice address left_margin = 350; writeText(cb, "Invoice address", left_margin, top_margin, f_cb, 10); writeText(cb, drHead["invCustomerName"].ToString(), left_margin, top_margin - 12, f_cn, 10); writeText(cb, drHead["invAddress1"].ToString(), left_margin, top_margin - 24, f_cn, 10); writeText(cb, drHead["invAddress2"].ToString(), left_margin, top_margin - 36, f_cn, 10); writeText(cb, drHead["invAddress3"].ToString(), left_margin, top_margin - 48, f_cn, 10); writeText(cb, drHead["invZipcode"].ToString(), left_margin, top_margin - 60, f_cn, 10); writeText(cb, drHead["invCity"].ToString() + ", " + drHead["invCountry"].ToString(), left_margin + 65, top_margin - 60, f_cn, 10); // Write out invoice terms details left_margin = 40; top_margin = 620; writeText(cb, "Payment terms", left_margin, top_margin, f_cb, 10); writeText(cb, drHead["payTerms"].ToString(), left_margin, top_margin - 12, f_cn, 10); writeText(cb, "Delivery terms", left_margin + 200, top_margin, f_cb, 10); writeText(cb, drHead["delTerms"].ToString(), left_margin + 200, top_margin - 12, f_cn, 10); writeText(cb, "Transport terms", left_margin + 350, top_margin, f_cb, 10); writeText(cb, drHead["delTransportTerms"].ToString(), left_margin + 350, top_margin - 12, f_cn, 10); // Move down left_margin = 40; top_margin = 590; writeText(cb, "Order reference", left_margin, top_margin, f_cb, 10); writeText(cb, drHead["orderReference"].ToString(), left_margin, top_margin - 12, f_cn, 10); writeText(cb, "Customer marking", left_margin + 200, top_margin, f_cb, 10); writeText(cb, drHead["customerMarking"].ToString(), left_margin + 200, top_margin - 12, f_cn, 10); writeText(cb, "Salesman", left_margin + 350, top_margin, f_cb, 10); writeText(cb, drHead["salesman"].ToString(), left_margin + 350, top_margin - 12, f_cn, 10); // NOTE! You need to call the EndText() method before we can write graphics to the document! cb.EndText(); // Separate the header from the rows with a line // Draw a line by setting the line width and position cb.SetLineWidth(0f); cb.MoveTo(40, 570); cb.LineTo(560, 570); cb.Stroke(); // Don't forget to call the BeginText() method when done doing graphics! cb.BeginText(); // Before we write the lines, it's good to assign a "last position to write" // variable to validate against if we need to make a page break while outputting. // Change it to 510 to write to test a page break; the fourth line on a new page int lastwriteposition = 100; // Loop thru the rows in the rows table // Start by writing out the line headers top_margin = 550; left_margin = 40; // Line headers writeText(cb, "Item", left_margin, top_margin, f_cb, 10); writeText(cb, "Description", left_margin + 70, top_margin, f_cb, 10); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Qty", left_margin + 415, top_margin, 0); writeText(cb, "Unit", left_margin + 420, top_margin, f_cb, 10); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, "Price", left_margin + 495, top_margin, 0); writeText(cb, "Curr", left_margin + 500, top_margin, f_cb, 10); // First item line position starts here top_margin = 538; // Loop thru the table of items and set the linespacing to 12 points. // Note that we use the -= operator, the coordinates goes from the bottom of the page! foreach (DataRow drItem in invoice.GetInvoiceRows().Rows) { writeText(cb, drItem["itemId"].ToString(), left_margin, top_margin, f_cn, 10); writeText(cb, drItem["itemDescription"].ToString(), left_margin + 70, top_margin, f_cn, 10); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, drItem["invoicedQuantity"].ToString(), left_margin + 415, top_margin, 0); writeText(cb, drItem["unit"].ToString(), left_margin + 420, top_margin, f_cn, 10); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, drItem["price"].ToString(), left_margin + 495, top_margin, 0); writeText(cb, drItem["currency"].ToString(), left_margin + 500, top_margin, f_cn, 10); // This is the line spacing, if you change the font size, you might want to change this as well. top_margin -= 12; // Implement a page break function, checking if the write position has reached the lastwriteposition if (top_margin <= lastwriteposition) { // We need to end the writing before we change the page cb.EndText(); // Make the page break document.NewPage(); // Start the writing again cb.BeginText(); // Assign the new write location on page two! // Here you might want to implement a new header function for the new page top_margin = 780; } } // Okay, write out the totals table // Here you might want to do some page break scenarios, as well: // Example: // Calculate how many rows you are about to print and see if they fit before the lastwriteposition, // then decide how to do; write some on first page, then the rest on second page or perhaps all the // total lines after the page break. // We are not doing this here, we just write them out 80 points below the last writed item row top_margin -= 80; left_margin = 350; // First the headers writeText(cb, "Invoice line totals", left_margin, top_margin, f_cb, 10); writeText(cb, "Freight fee", left_margin, top_margin - 12, f_cb, 10); writeText(cb, "VAT amount", left_margin, top_margin - 24, f_cb, 10); writeText(cb, "Invoice grand total", left_margin, top_margin - 48, f_cb, 10); // Move right to write out the values left_margin = 540; // Write out the invoice currency and values in regular text cb.SetFontAndSize(f_cn, 10); string curr = drTotal["currency"].ToString(); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, curr, left_margin, top_margin, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, curr, left_margin, top_margin - 12, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, curr, left_margin, top_margin - 24, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, curr, left_margin, top_margin - 48, 0); left_margin = 535; cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, drTotal["invoicedAmount"].ToString(), left_margin, top_margin, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, drTotal["freightCharge"].ToString(), left_margin, top_margin - 12, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, drTotal["VAT"].ToString(), left_margin, top_margin - 24, 0); cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, drTotal["totalAmount"].ToString(), left_margin, top_margin - 48, 0); // End the writing of text cb.EndText(); // Close the document, the writer and the filestream! document.Close(); writer.Close(); fs.Close(); //lblMsg.Text = "Invoiced saved to the invoice folder. Good job!"; } } catch (Exception rror) { //lblMsg.Text = rror.Message; } }
static public void CreatePdf(member NewMember) { string fileNameExisting = @"C:\Users\USER\Desktop\test\טופס_הצטרפות.pdf"; string fileNameNew = @"C:\Users\USER\Desktop\test\" + NewMember.Request_ID.ToString() + "\\form.pdf"; //PdfReader reader = new iTextSharp.text.pdf.PdfReader(fileNameExisting); //for (int i = 1; i <= reader.NumberOfPages; i++) //{ // Rectangle dim = reader.GetPageSize(i); // int[] xy = new int[] { (int)dim.Width, (int)dim.Height }; //} // open the reader PdfReader reader = new PdfReader(fileNameExisting); Rectangle size = reader.GetPageSizeWithRotation(1); Document document = new Document(size); // open the writer FileStream fs = new FileStream(fileNameNew, FileMode.Create, FileAccess.Write); PdfWriter writer = PdfWriter.GetInstance(document, fs); document.Open(); // the pdf content PdfContentByte cb = writer.DirectContent; // select the font properties BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.SetColorFill(BaseColor.BLACK); cb.SetFontAndSize(bf, 10); // write the text in the pdf content cb.BeginText(); string name = NewMember.First_Name; // put the alignment and coordinates here cb.ShowTextAligned(1, name, 500, 535, 0); cb.EndText(); cb.BeginText(); string lastname = NewMember.Last_Name; cb.ShowTextAligned(2, lastname, 430, 535, 0); cb.EndText(); cb.BeginText(); string Identity_Card = NewMember.Identity_Card; cb.ShowTextAligned(3, Identity_Card, 213, 535, 0); cb.EndText(); if (!string.IsNullOrEmpty(NewMember.Address)) { cb.BeginText(); string Address = NewMember.Address; cb.ShowTextAligned(4, Address, 480, 500, 0); cb.EndText(); } cb.BeginText(); string Phone = NewMember.Phone; cb.ShowTextAligned(5, Phone, 495, 450, 0); cb.EndText(); if (!string.IsNullOrEmpty(NewMember.Email)) { cb.BeginText(); string Email = NewMember.Email; cb.ShowTextAligned(6, Email, 220, 455, 0); cb.EndText(); } cb.BeginText(); string Bank_Account_ = NewMember.Bank_Account_; // put the alignment and coordinates here cb.ShowTextAligned(7, Bank_Account_, 289, 251, 0); cb.EndText(); // create the new page and add it to the pdf PdfImportedPage page = writer.GetImportedPage(reader, 1); cb.AddTemplate(page, 0, 0); // close the streams and voilá the file should be changed :) document.Close(); fs.Close(); writer.Close(); reader.Close(); //using (var existingFileStream = new FileStream(fileNameExisting, FileMode.Open)) //using (var newFileStream = new FileStream(fileNameNew, FileMode.Create)) //{ // // Open existing PDF // var pdfReader = new PdfReader(existingFileStream); // // PdfStamper, which will create // var stamper = new PdfStamper(pdfReader, newFileStream); // var form = stamper.AcroFields; // var fieldKeys = form.Fields.Keys; // foreach (string fieldKey in fieldKeys) // { // form.SetField(fieldKey, "REPLACED!"); // } // // "Flatten" the form so it wont be editable/usable anymore // stamper.FormFlattening = true; // // You can also specify fields to be flattened, which // // leaves the rest of the form still be editable/usable // stamper.PartialFormFlattening("field1"); // stamper.Close(); // pdfReader.Close(); //} }
public void MergeFileslab(string destinationFile, string[] sourceFiles) { if (System.IO.File.Exists(destinationFile)) { System.IO.File.Delete(destinationFile); } string[] sSrcFile; sSrcFile = new string[2]; string[] arr = new string[2]; for (int i = 0; i <= sourceFiles.Length - 1; i++) { if (sourceFiles[i] != null) { if (sourceFiles[i].Trim() != "") { arr[i] = sourceFiles[i].ToString(); } } } if (arr != null) { sSrcFile = new string[2]; for (int ic = 0; ic <= arr.Length - 1; ic++) { sSrcFile[ic] = arr[ic].ToString(); } } try { int f = 0; PdfReader reader = new PdfReader(sSrcFile[f]); int n = reader.NumberOfPages; //Response.Write("There are " + n + " pages in the original file."); Document document = new Document(PageSize.A4); PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create)); document.Open(); PdfContentByte cb = writer.DirectContent; PdfImportedPage page; int rotation; while (f < sSrcFile.Length) { int i = 0; while (i < n) { i++; if (f == 0) { document.SetPageSize(PageSize.A4); } else if (f == 1) { document.SetPageSize(PageSize.A5.Rotate()); } document.NewPage(); page = writer.GetImportedPage(reader, i); rotation = reader.GetPageRotation(i); if (rotation == 90 || rotation == 270) { cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height); } else { cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); } //Response.Write("\n Processed page " + i); } f++; if (f < sSrcFile.Length) { reader = new PdfReader(sSrcFile[f]); n = reader.NumberOfPages; //Response.Write("There are " + n + " pages in the original file."); } } //Response.Write("Success"); document.Close(); } catch (Exception e) { //Response.Write(e.Message); } }
private static bool Overlay(dynamic overlay, string filename) { string inputFile = ServiceCfg.PdfModel; string cardFolder = Path.Combine(ServiceCfg.OutputFolderPath, @"pages\"); if (!PdfManager.CheckFolder(cardFolder, true)) { return(false); } string outFile = Path.Combine(cardFolder, "CTP_" + filename); //Creation du reader et du document pour lire le document PDF original PdfReader reader = new PdfReader(inputFile); Document inputDoc = new Document(reader.GetPageSizeWithRotation(1)); using (FileStream fs = new FileStream(outFile, FileMode.Create)) { //Creation du PDF Writer pour créer le nouveau Document PDF PdfWriter outputWriter = PdfWriter.GetInstance(inputDoc, fs); inputDoc.Open(); //Creation du Content Byte pour tamponner le PDF writer PdfContentByte cb1 = outputWriter.DirectContent; //Obtien le document PDF à utiliser comme superposition PdfReader overlayReader = new PdfReader(overlay); PdfImportedPage overLay = outputWriter.GetImportedPage(overlayReader, 1); //Obtention de la rotation de page de superposition int overlayRotation = overlayReader.GetPageRotation(1); int n = reader.NumberOfPages; //liste des numéros de pages à marquer dans le modèle List <int> pagesList = GetModelPages2Overlay(n); int i = 1; while (i <= n) { //S'assurer que la taille de la nouvelle page correspond à celle du document d'origine inputDoc.SetPageSize(reader.GetPageSizeWithRotation(i)); inputDoc.NewPage(); PdfImportedPage page = outputWriter.GetImportedPage(reader, i); int rotation = reader.GetPageRotation(i); //Ajout de la page PDF originale avec la bonne rotation if (rotation == 90 || rotation == 270) { cb1.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height); } else { //cb1.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); cb1.AddTemplate(page, 0, 0, true); } //si la page en cours est à marquer if (pagesList.Contains(i)) { //Ajout de la superposition avec la bonne rotation if (overlayRotation == 90 || overlayRotation == 270) { cb1.AddTemplate(overLay, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height); } else { //cb1.AddTemplate(overLay, 1f, 0, 0, 1f, 0, 0); cb1.AddTemplate(overLay, float.Parse(ServiceCfg.OverlayX.ToString()), float.Parse(ServiceCfg.OverlayY.ToString()), true); } } //Increment de page i++; } //Fermeture du fichier d'entrée inputDoc.Close(); //on garde le fichier de sortie _lastPdf = outFile; //Fermeture du reader pour le fichier de superposition overlayReader.Close(); } reader.Close(); return(true); }
} //Cierra crear PDF Banco /// <summary> /// Crea PDF para las Cargas de las Sucursales /// </summary> /// <param name="carga">Objeto CargaSucursal con los datos de la Carga de la Sucursal</param> public void CrearPDFSucursal() //Abre crear PDF Sucursal { // mostrarDatosCargaSucursal(); CargaSucursal suc = _carga_sucursal; DateTime hoy = DateTime.Today; string actual = hoy.ToString("dd/MM/yyyy"); string destinopdf = @"\\10.120.131.100\Manifiestos\SUC-" + suc.Manifiesto + ".pdf"; //DEFINE NOMBRE Y UBICACION DEL PDF QUE SE DESEA CREAR Stream output = new FileStream(destinopdf, FileMode.Create, FileAccess.Write); string plantilla = @"\\10.120.131.100\Releases\manifiesto.pdf"; //DEFINE LA UBICACION Y EL NOMBRE DE LA PLANTILLA A USAR PdfReader readerBicycle = null; Document documento = new Document(); FileStream theFile = new FileStream(plantilla, FileMode.Open, FileAccess.Read); PdfWriter writer = PdfWriter.GetInstance(documento, output); documento.Open(); readerBicycle = new PdfReader(theFile); PdfTemplate background = writer.GetImportedPage(readerBicycle, 1); documento.NewPage(); _pcb = writer.DirectContentUnder; _pcb.AddTemplate(background, 0, 0); _pcb = writer.DirectContent; _pcb.BeginText(); SetFontBarCode(11); //ESTABLECE LA FUENTE E IMPRIME CON LA FUENTE BARCODE HASTA SER CAMBIADA PrintText("*" + suc.Manifiesto + "*", 250, 700); //Imprime codigo de barras SetFont(13); PrintText(suc.Manifiesto.ToString(), 450, 705); SetFont(8); //CAMBIAMOS LA FUENTE montoLetrasPdf(montoenletras); //Imprime monto total en letras y valida el tamaño PrintText("TIPO", 355, 670); //Imprime tipo de cambio PrintText("CANT", 415, 1670); //Cantidad depositos //PrintText("MANIS", 480, 670); //Imprime tipo de cambio //LADO IZQUIERDO PrintText(suc.Sucursal.ToString(), 87, 632); //Origen de los fondos PrintText("BAC San José", 87, 610); //Origen de los fondos PrintText("Centro de Dist. Cipréses", 87, 589); //Origen de los fondos PrintText("CURRIDABAT", 87, 568); //Origen de los fondos PrintText("SAN JOSE", 202, 568); //Provincia PrintText(suc.Cajero.ToString(), 87, 547); //Nombre de Persona que preparó cargamento PrintText(suc.Fecha_asignada.ToShortDateString(), 265, 547); //Fecha de Entrega PrintText(suc.Cajero.ToString(), 87, 525); //Entregado a PrintText(suc.ToString(), 252, 525); //Oficinas PrintText("Centro de Dist. Cipreses", 87, 505); //Direccion PrintText("CURRIDABAT", 87, 483); //Origen de los fondos PrintText("SAN JOSE", 225, 483); //Provincia int bultos = 0; if (suc.Cartuchos.Count > 5) { if (suc.Monto_asignado_colones > 0) { PrintText(("CRC " + suc.Monto_asignado_colones.ToString("N2")), 225, 454); /*MONTO colones*/ } if (suc.Monto_asignado_dolares > 0) { PrintText(("USD " + suc.Monto_asignado_dolares.ToString("N2")), 225, 432); /*MONTO dolares*/ } if (suc.Monto_asignado_dolares > 0) { PrintText(("EUR " + suc.Monto_asignado_dolares.ToString("N2")), 225, 411); /*MONTO Euros*/ } } else { int fila = 454; foreach (CartuchoCargaSucursal cartucho in suc.Cartuchos) { switch (cartucho.Denominacion.Moneda) { case Monedas.Colones: PrintText(("CRC " + cartucho.Monto_carga.ToString("N2")), 225, fila); /*MONTO colones*/ // PrintText(cartucho.Marchamo.ToString(), 87, fila); /*MONTO colones*/ PrintText("1", 200, fila); /*BULTOS*/ PrintText("B", 175, fila); /*BT*/ fila = fila - 22; bultos++; break; case Monedas.Dolares: PrintText(("USD " + cartucho.Monto_carga.ToString("N2")), 225, fila); /*MONTO dolares*/ PrintText(cartucho.Marchamo.ToString(), 87, fila); /*MONTO dolares*/ PrintText("1", 200, fila); /*BULTOS*/ PrintText("B", 175, fila); /*BT*/ fila = fila - 22; bultos++; break; case Monedas.Euros: PrintText(("EUR " + cartucho.Monto_carga.ToString("N2")), 225, fila); /*MONTO euros*/ PrintText(cartucho.Marchamo.ToString(), 87, fila); /*MONTO euros*/ PrintText("1", 200, fila); /*BULTOS*/ PrintText("B", 175, fila); /*BT*/ fila = fila - 22; bultos++; break; } } } PrintText("CRC " + lblGranTotal.Text, 225, 315); //LADO DERECHO PrintText(lblPortavalorRecibe.Text, 320, 632); //Nombre portavalor recibe PrintText(lblPortavalorRuta.Text, 320, 578); //Responsable Ruta PrintText(lblnumeroatm.Text, 358, 562); //Numero de Banco PrintText(suc.Monto_carga_colones.ToString("N2"), 438, 538); //monto descarga colones PrintText(suc.Monto_carga_dolares.ToString("N2"), 438, 518); //monto descarga dolares PrintText(suc.Ruta.ToString(), 440, 610); //Ruta PrintText(suc.ToString(), 332, 610); PrintText(suc.Hora_Entrada.ToShortTimeString(), 346, 610); PrintText(suc.Hora_Salida.ToShortTimeString(), 385, 610); PrintText(suc.Fecha_asignada.ToShortDateString(), 475, 610); //Fecha PrintText(lblnumeroatm.Text, 358, 562); //Numero de ATM PrintText(("CRC " + suc.Monto_carga_colones.ToString("N2")), 438, 538); //monto descarga colones PrintText(("USD " + suc.Monto_carga_dolares.ToString("N2")), 438, 518); //monto descarga dolares PrintText(lblBolsaMarchamo.Text, 438, 498); //Numero de marchamo de rechazo PrintText(lblComentario.Text, 325, 450); PrintText(lblTulaBNA.Text, 438, 478); } //Cierra crear PDF Sucursal
public void Merge(Stream outputStream) { if (outputStream == null || !outputStream.CanWrite) { throw new Exception("OutputStream es nulo o no se puede escribir en éste."); } Document newDocument = null; int rotation; try { newDocument = new Document(); PdfWriter pdfWriter = PdfWriter.GetInstance(newDocument, outputStream); newDocument.Open(); PdfContentByte pdfContentByte = pdfWriter.DirectContent; if (EnablePagination) { documents.ForEach(delegate(PdfReader doc) { totalPages += doc.NumberOfPages; }); } int currentPage = 1; foreach (PdfReader pdfReader in documents) { for (int page = 1; page <= Math.Min(pdfReader.NumberOfPages, 2); page++) { newDocument.SetPageSize(pdfReader.GetPageSizeWithRotation(page)); newDocument.NewPage(); PdfImportedPage importedPage = pdfWriter.GetImportedPage(pdfReader, page); rotation = pdfReader.GetPageRotation(page); if (rotation == 90 || rotation == 270) { pdfContentByte.AddTemplate(importedPage, 0, -1f, 1f, 0, 0, pdfReader.GetPageSizeWithRotation(page).Height); } else { pdfContentByte.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0); } if (EnablePagination) { pdfContentByte.BeginText(); pdfContentByte.SetFontAndSize(baseFont, 9); pdfContentByte.ShowTextAligned(PdfContentByte.ALIGN_CENTER, string.Format("{0} de {1}", currentPage++, totalPages), 520, 5, 0); pdfContentByte.EndText(); } } } } finally { outputStream.Flush(); if (newDocument != null) { newDocument.Close(); } outputStream.Close(); } }
public void WriteAbout(int n) { string pasta; pasta = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath; if (!Directory.Exists(Path.Combine(pasta, "ErgoMobile", "Exported", "temp", "new"))) { Directory.CreateDirectory(Path.Combine(pasta, "ErgoMobile", "Exported", "temp", "new")); } char c = (char)(41 + n); string oldFile; string newFile; if (n >= 0) { oldFile = Path.Combine(pasta, "ErgoMobile", "Exported", "temp", (n + 1) + c + ".pdf"); newFile = Path.Combine(pasta, "ErgoMobile", "Exported", "temp", "new", (n + 1) + c + ".pdf"); } else { oldFile = Path.Combine(pasta, "ErgoMobile", "Exported", "temp", "99total.pdf"); newFile = Path.Combine(pasta, "ErgoMobile", "Exported", "temp", "new", "99total.pdf"); } // open the reader PdfReader reader = new PdfReader(oldFile); Rectangle size = reader.GetPageSizeWithRotation(1); Document document = new Document(size); // open the writer if (File.Exists(newFile)) { File.Delete(newFile); } FileStream fs = new FileStream(newFile, FileMode.Create, FileAccess.Write); PdfWriter writer = PdfWriter.GetInstance(document, fs); document.Open(); // the pdf content PdfContentByte cb = writer.DirectContent; // select the font properties BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.SetColorFill(BaseColor.DARK_GRAY); cb.SetFontAndSize(bf, 17); // write the text in the pdf content string Text = "Total respondido: " + (mr + r + reg + b + mb) + " Não respondido: " + nr; if (lang == "en") { Text = "Total answered: " + (mr + r + reg + b + mb) + " Not answered: " + nr; } cb.BeginText(); // put the alignment and coordinates here cb.ShowTextAligned(1, Text, 296, 760, 0); cb.EndText(); cb.BeginText(); Text = "Muito ruim: " + mr + " Ruim: " + r + " Regular: " + reg + " Bom: " + b + " Muito bom: " + mb; if (lang == "en") { Text = "Too bad: " + mr + " Bad: " + r + " Regular: " + reg + " Good: " + b + " Very good: " + mb; } // put the alignment and coordinates here cb.ShowTextAligned(1, Text, 296, 740, 0); cb.EndText(); // create the new page and add it to the pdf PdfImportedPage page = writer.GetImportedPage(reader, 1); cb.AddTemplate(page, 0, 0); // close the streams and voilá the file should be changed :) document.Close(); fs.Close(); writer.Close(); reader.Close(); }
static int borderThickness = 1; // It's just 1. Won't really change, but whatever. If you change it, things will get fucky. public static bool MakePDF(Ragecomic comic, string pdffile) { using (System.IO.FileStream fs = new FileStream(pdffile, FileMode.Create)) { int rows = (int)Math.Ceiling((double)comic.panels / 2); int width = rowWidth * 2 + borderThickness * 3; int height = rowHeight * rows + borderThickness * rows + borderThickness; // 239 per row, plus 1 pixel border per row, plus 1 pixel extra border ZipFile drawImageZip = new ZipFile(); bool hasDrawImages = comic.items.getDrawImageCount() > 0; if (hasDrawImages) { drawImageZip.Dispose(); string addition = ""; int nr = 1; while (File.Exists(pdffile + ".drawimages" + addition + ".zip")) { addition = "_" + (nr++).ToString(); } drawImageZip = new ZipFile(pdffile + ".drawimages" + addition + ".zip"); } // Create an instance of the document class which represents the PDF document itself. Rectangle pageSize = new Rectangle(width, height); Document document = new Document(pageSize, 0, 0, 0, 0); // Create an instance to the PDF file by creating an instance of the PDF // Writer class using the document and the filestrem in the constructor. PdfWriter writer = PdfWriter.GetInstance(document, fs); document.AddAuthor("Derp"); document.AddCreator("RagemakerToPDF"); document.AddKeywords("rage, comic"); document.AddSubject("A rage comic"); document.AddTitle("A rage comic"); // Open the document to enable you to write to the document document.Open(); PdfContentByte cb = writer.DirectContent; // Fill background with white Rectangle rect = new iTextSharp.text.Rectangle(0, 0, width, height); rect.BackgroundColor = new BaseColor(255, 255, 255); cb.Rectangle(rect); // Draw grid on bottom if it isn't set to be on top. if (!comic.gridAboveAll && comic.showGrid) { DrawGrid(cb, width, height, rows, comic); } //List<MyMedia.FontFamily> families = MyMedia.Fonts.SystemFontFamilies.ToList(); // This was a neat idea, but it's much too slow //List<string> files = FontFinder.GetFilesForFont("Courier New").ToList(); //string filename = FontFinder.GetSystemFontFileName(families[0].) //Draw.Font testFont = new Draw.Font(new Draw.FontFamily("Courier New"),12f,Draw.FontStyle.Regular | Draw.FontStyle.Bold); string courierPath = FontFinder.GetSystemFontFileName("Courier New", true); string courierBoldPath = FontFinder.GetSystemFontFileName("Courier New", true, Draw.FontStyle.Bold); string tahomaPath = FontFinder.GetSystemFontFileName("Tahoma", true, Draw.FontStyle.Bold); // Define base fonts Font[] fonts = new Font[3]; fonts[0] = new Font(BaseFont.CreateFont(courierPath, BaseFont.CP1252, BaseFont.EMBEDDED)); fonts[1] = new Font(BaseFont.CreateFont(courierBoldPath, BaseFont.CP1252, BaseFont.EMBEDDED)); fonts[2] = new Font(BaseFont.CreateFont(tahomaPath, BaseFont.CP1252, BaseFont.EMBEDDED)); /*fonts[0] = BaseFont.CreateFont("fonts/TRCourierNew.ttf", BaseFont.CP1252, BaseFont.EMBEDDED); * fonts[1] = BaseFont.CreateFont("fonts/TRCourierNewBold.ttf", BaseFont.CP1252, BaseFont.EMBEDDED); * fonts[2] = new Font(BaseFont.CreateFont("fonts/Tahoma-Bold.ttf", BaseFont.CP1252, BaseFont.EMBEDDED));*/ int drawimageindex = 0; int index = 0; foreach (var item in comic.items) { if (item is Face) { Face face = (Face)item; Image pdfImage; System.Drawing.Image faceImage; // If mirroring is necessary, we have to read the image via C# and use RotateFlip, as iTextSharp doesn't support mirroring. if (face.mirrored) { // If it's a JPEG, open it with Flux.JPEG.Core, because the internal JPEG decoder (and also LibJpeg.NET) creates weird dithering artifacts with greyscale JPGs, which some of the rage faces are. if (Path.GetExtension(face.file).ToLower() == ".jpeg" || Path.GetExtension(face.file).ToLower() == ".jpg") { FileStream jpegstream = File.OpenRead("images/" + face.file); FluxJpeg.Core.DecodedJpeg myJpeg = new JpegDecoder(jpegstream).Decode(); // Only use this JPEG decoder if the colorspace is Gray. Otherwise the normal one is just fine. if (myJpeg.Image.ColorModel.colorspace == FluxJpeg.Core.ColorSpace.Gray) { myJpeg.Image.ChangeColorSpace(FluxJpeg.Core.ColorSpace.YCbCr); faceImage = myJpeg.Image.ToBitmap(); } else { faceImage = System.Drawing.Image.FromFile("images/" + face.file); } } else { faceImage = System.Drawing.Image.FromFile("images/" + face.file); } // Apply mirroring faceImage.RotateFlip(System.Drawing.RotateFlipType.RotateNoneFlipX); pdfImage = Image.GetInstance(faceImage, System.Drawing.Imaging.ImageFormat.Png); } else { // Just let iTextSharp handle it if no mirroring is required. Will also save space (presumably) pdfImage = Image.GetInstance("images/" + face.file); } pdfImage.ScalePercent(face.scalex * 100, face.scaley * 100); pdfImage.Rotation = -(float)Math.PI * face.rotation / 180.0f; pdfImage.SetAbsolutePosition(item.x, (height - item.y) - pdfImage.ScaledHeight); // Set opacity to proper value if (face.opacity < 1) { PdfGState graphicsState = new PdfGState(); graphicsState.FillOpacity = face.opacity; cb.SetGState(graphicsState); } cb.AddImage(pdfImage); // Set back to normal if (face.opacity < 1) { PdfGState graphicsState = new PdfGState(); graphicsState.FillOpacity = 1f; cb.SetGState(graphicsState); } } else if (item is DrawImage) { DrawImage drawimage = (DrawImage)item; drawImageZip.AddEntry("drawimage_" + (drawimageindex++).ToString() + ".png", drawimage.imagedata); System.Drawing.Image pngImage = System.Drawing.Image.FromStream(new MemoryStream(drawimage.imagedata)); Image pdfImage = Image.GetInstance(pngImage, System.Drawing.Imaging.ImageFormat.Png); // Rotation is NOT to be applied. Ragemaker actually has a bug that causes it to save rotated images in their rotated form, but save the rotation value anyway // Thus rotating the image by the rotation value will actually rotate them double compared to what they originally looked like // The irony is that ragemaker *itself* cannot properly load an xml it created with this rotation value, as it will also apply the rotation // As such, this tool is currently the only way to correctly display that .xml file as it was originally meant to look, not even ragemaker itself can properly load it again. //pdfImage.Rotation = -(float)Math.PI * item.rotation / 180.0f; pdfImage.SetAbsolutePosition(item.x, (height - item.y) - pdfImage.ScaledHeight); // Opacity likewise seems to be baked in, and in fact the opacity value doesn't even exist. // Implementing it anyway, in case it ever becomes a thing. if (drawimage.opacity < 1) { PdfGState graphicsState = new PdfGState(); graphicsState.FillOpacity = drawimage.opacity; cb.SetGState(graphicsState); } cb.AddImage(pdfImage); // Set back to normal if (drawimage.opacity < 1) { PdfGState graphicsState = new PdfGState(); graphicsState.FillOpacity = 1f; cb.SetGState(graphicsState); } } else if (item is Text) { int padding = 4; Text text = (Text)item; // Create template PdfTemplate xobject = cb.CreateTemplate(text.width, text.height); // Background color (if set) if (text.bgOn) { Rectangle bgRectangle = new Rectangle(0, 0, text.width, text.height); System.Drawing.Color bgColor = System.Drawing.ColorTranslator.FromHtml(text.bgColor); rect.BackgroundColor = new BaseColor(bgColor.R, bgColor.G, bgColor.B, (int)Math.Floor(text.opacity * 255)); xobject.Rectangle(rect); } // Create text Rectangle textangle = new Rectangle(padding, 0, text.width - padding, text.height); ColumnText ct = new ColumnText(xobject); ct.SetSimpleColumn(textangle); Paragraph paragraph = new Paragraph(text.text); Font myFont = fonts[text.style]; // More specific treatment if it's an AnyFont element which allows the user to select any font and styles, not just the normal 3 presets // This isn't perfect, as the current FontFinder doesn't indicate whether he actually found an Italic/Bold typeface, hence it's not possible // to determine whether faux-italic/faux-bold should be applied. Currently it will only work correctly if each used font has a specific typeface // for the needed styles (bold or italic), otherwise incorrect results. // TODO Fix, for example let FontFinder return array of strings, one of which is indicating the suffix that was found. if (text is AnyFontText) { AnyFontText anyfont = (AnyFontText)text; string fontname = anyfont.font; string fontfile = ""; if (anyfont.bold) { fontfile = FontFinder.GetSystemFontFileName(fontname, true, Draw.FontStyle.Bold); int fontStyle = 0; if (anyfont.italic) { fontStyle |= Font.ITALIC; } if (anyfont.underline) { fontStyle |= Font.UNDERLINE; } myFont = new Font(BaseFont.CreateFont(fontfile, BaseFont.CP1252, BaseFont.EMBEDDED), 100f, fontStyle); } else if (anyfont.italic) { fontfile = FontFinder.GetSystemFontFileName(fontname, true, Draw.FontStyle.Italic); int fontStyle = 0; if (anyfont.underline) { fontStyle |= Font.UNDERLINE; } myFont = new Font(BaseFont.CreateFont(fontfile, BaseFont.CP1252, BaseFont.EMBEDDED), 100f, fontStyle); } else { fontfile = FontFinder.GetSystemFontFileName(fontname, true, Draw.FontStyle.Regular); int fontStyle = 0; if (anyfont.underline) { fontStyle |= Font.UNDERLINE; } myFont = new Font(BaseFont.CreateFont(fontfile, BaseFont.CP1252, BaseFont.EMBEDDED), 100f, fontStyle); } } myFont.Size = text.size; System.Drawing.Color color = (System.Drawing.Color)(new System.Drawing.ColorConverter()).ConvertFromString(text.color); myFont.Color = new BaseColor(color.R, color.G, color.B, (int)Math.Floor(text.opacity * 255)); paragraph.Font = myFont; paragraph.Alignment = text.align == Text.ALIGN.LEFT ? PdfContentByte.ALIGN_LEFT : (text.align == Text.ALIGN.RIGHT ? PdfContentByte.ALIGN_RIGHT : PdfContentByte.ALIGN_CENTER); paragraph.SetLeading(0, 1.12f); ct.AddElement(paragraph); ct.Go(); // Angle to radians float angle = (float)Math.PI * text.rotation / 180.0f; // Calculate Bounding Box size for correct placement later GraphicsPath gp = new GraphicsPath(); gp.AddRectangle(new System.Drawing.Rectangle(0, 0, (int)Math.Round(text.width), (int)Math.Round(text.height))); Matrix translateMatrix = new Matrix(); translateMatrix.RotateAt(text.rotation, new System.Drawing.PointF(text.width / 2, text.height / 2)); gp.Transform(translateMatrix); var gbp = gp.GetBounds(); float newWidth = gbp.Width, newHeight = gbp.Height; // Create correct placement // Background info: I rotate around the center of the text box, thus the center of the text box is what I attempt to place correctly with the initial .Translate() AffineTransform transform = new AffineTransform(); transform.Translate(item.x + newWidth / 2 - text.width / 2, height - (item.y + newHeight / 2 - text.height / 2) - text.height); transform.Rotate(-angle, text.width / 2, text.height / 2); cb.AddTemplate(xobject, transform); } index++; } if (comic.gridAboveAll && comic.showGrid) { DrawGrid(cb, width, height, rows, comic); } //document.Add(new Paragraph("Hello World!")); // Close the document document.Close(); // Close the writer instance writer.Close(); // Always close open filehandles explicity fs.Close(); if (hasDrawImages) { drawImageZip.Save(); } drawImageZip.Dispose(); } return(false); }
protected void AdjustPage(string filename, int currentPage, string direction, string outFile) { PdfReader reader; Document document = new Document(); // Define the output place, and add the document to the stream PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(outFile, FileMode.Create)); // Open document document.Open(); // PDF ContentByte PdfContentByte cb = writer.DirectContent; // PDF import page PdfImportedPage newPage; reader = new PdfReader(@"d:\ftpserver\" + filename); int iPageNum = reader.NumberOfPages; for (int j = 1; j <= iPageNum; j++) { if (direction == "down") { if (currentPage == j) { document.NewPage(); newPage = writer.GetImportedPage(reader, j + 1); cb.AddTemplate(newPage, 0, 0); document.NewPage(); newPage = writer.GetImportedPage(reader, j); cb.AddTemplate(newPage, 0, 0); j++; } else { document.NewPage(); newPage = writer.GetImportedPage(reader, j); cb.AddTemplate(newPage, 0, 0); } } if (direction == "up") { if (currentPage == j + 1) { document.NewPage(); newPage = writer.GetImportedPage(reader, j + 1); cb.AddTemplate(newPage, 0, 0); document.NewPage(); newPage = writer.GetImportedPage(reader, j); cb.AddTemplate(newPage, 0, 0); j++; } else { document.NewPage(); newPage = writer.GetImportedPage(reader, j); cb.AddTemplate(newPage, 0, 0); } } //if (direction == "delete") by panhuaguo 2016-4-19 梁总决定不让删除原始文件的某一页 //{ // if (currentPage != j) // { // document.NewPage(); // newPage = writer.GetImportedPage(reader, j); // cb.AddTemplate(newPage, 0, 0); // } //} } document.Close(); }
private void CompletePage1AndSend(Student student) { string fileNameExisting = ConfigurationManager.AppSettings.Get("ApplicationFormFilePath") + "TemplatePage1.pdf"; string fileNameNew = ConfigurationManager.AppSettings.Get("ApplicationFormFilePath") + "App_" + student.ReferenceNumber + ".pdf"; // open the reader PdfReader reader = new PdfReader(fileNameExisting); Rectangle size = reader.GetPageSizeWithRotation(1); Document document = new Document(size); // open the writer FileStream fs = new FileStream(fileNameNew, FileMode.Create, FileAccess.Write); PdfWriter writer = PdfWriter.GetInstance(document, fs); document.Open(); // the pdf content PdfContentByte cb = writer.DirectContent; // select the font properties BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.SetColorFill(BaseColor.DARK_GRAY); cb.SetFontAndSize(bf, 8); // write the text in the pdf content cb.BeginText(); //line1 cb.ShowTextAligned(3, student.CommencementDate.Value.ToShortDateString(), 140, 670, 0); cb.ShowTextAligned(3, student.EndDate.Value.ToShortDateString(), 450, 670, 0); //line2 cb.ShowTextAligned(3, student.MembershipNumber, 140, 650, 0); cb.ShowTextAligned(3, student.ReferenceNumber, 450, 650, 0); //line3 cb.ShowTextAligned(3, student.Surname, 140, 610, 0); cb.ShowTextAligned(3, student.Contribution.ToString(), 450, 610, 0); //line4 cb.ShowTextAligned(3, student.FirstNames, 140, 590, 0); Gender gender = entity.Genders.Where(p => p.IdGender == student.IdGender).FirstOrDefault(); cb.ShowTextAligned(3, gender.GenderDescription, 450, 590, 0); //line5 Title title = entity.Titles.Where(p => p.IdTitle == student.IdTitle).FirstOrDefault(); cb.ShowTextAligned(3, title.TitleAbbreviation, 110, 570, 0); MaritalStatuss status = entity.MaritalStatusses.Where(p => p.IdMaritalStatus == student.IdMaritalStatus).FirstOrDefault(); cb.ShowTextAligned(3, status.Description, 200, 570, 0); Country country = entity.Countries.Where(p => p.IdCountry == student.CountryOfIssue).FirstOrDefault(); cb.ShowTextAligned(3, country.Name, 450, 570, 0); //line6 cb.ShowTextAligned(3, student.DateOfBirth.Value.ToShortDateString(), 140, 550, 0); cb.ShowTextAligned(3, student.IDPassport, 450, 550, 0); //line7 StudentAddress postal = entity.StudentAddresses.Where(p => p.IdStudent == student.IdStudent && p.IsPostalAddress.Value).FirstOrDefault(); string postalAddy = postal != null ? postal.Address1 + ", " + postal.Address2 + ", " + postal.Address3 + ", " + postal.Address4 + ", " + entity.Provinces.Where(p => p.IdProvince == postal.IdProvince).FirstOrDefault().Name + " ," + postal.PostalCode : "Not provided."; cb.ShowTextAligned(3, postalAddy, 140, 530, 0); //line8 StudentAddress physical = entity.StudentAddresses.Where(p => p.IdStudent == student.IdStudent && !p.IsPostalAddress.Value).FirstOrDefault(); string physAddy = physical != null ? physical.Address1 + ", " + physical.Address2 + ", " + physical.Address3 + ", " + physical.Address4 + ", " + entity.Provinces.Where(p => p.IdProvince == physical.IdProvince).FirstOrDefault().Name + " ," + physical.PostalCode : "Not provided."; cb.ShowTextAligned(3, physAddy, 140, 500, 0); //line9 cb.ShowTextAligned(3, student.Email, 140, 480, 0); //line10 cb.ShowTextAligned(3, student.BusinessTelephone, 140, 460, 0); cb.ShowTextAligned(3, student.HomeTelephone, 450, 460, 0); //line11 cb.ShowTextAligned(3, student.Facsimile, 140, 440, 0); cb.ShowTextAligned(3, student.Cellular, 450, 440, 0); //line12 Institution ins = entity.Institutions.Where(p => p.IdInstitution == student.StudyInstitution).FirstOrDefault(); cb.ShowTextAligned(3, ins.InstitutionName, 140, 420, 0); cb.ShowTextAligned(3, student.StudentNumber, 450, 420, 0); //line13 cb.ShowTextAligned(3, student.IncomeAmount != null ? student.IncomeAmount.Value.ToString() : "n/a", 140, 375, 0); //group 14 List <StudentDependant> deps = entity.StudentDependants.Where(p => p.IdStudent == student.IdStudent).ToList(); if (deps != null) { int y = 350; foreach (var item in deps) { cb.ShowTextAligned(3, item.Name, 140, y, 0); cb.ShowTextAligned(3, item.Surname, 200, y, 0); DependantType type = entity.DependantTypes.Where(p => p.IdDependantType == item.IdDependantType).FirstOrDefault(); cb.ShowTextAligned(3, type != null ? type.DependantTypeDescription : "n/a", 260, y, 0); Gender gen = entity.Genders.Where(p => p.IdGender == item.IdGender).FirstOrDefault(); cb.ShowTextAligned(3, gen != null ? gen.GenderDescription : "n/a", 310, y, 0); cb.ShowTextAligned(3, item.DateOfBirth != null ? item.DateOfBirth.Value.ToShortDateString() : "n/a", 370, y, 0); y = y - 20; } } //group 15 cb.ShowTextAligned(3, student.MedicalQ1 != null ? "yes" : "no", 450, 205, 0); cb.ShowTextAligned(3, student.MedicalQ1 != null ? "yes" : "no", 450, 195, 0); cb.ShowTextAligned(3, student.MedicalQ1 != null ? "yes" : "no", 450, 185, 0); List <TreatmentDetail> meds = entity.TreatmentDetails.Where(p => p.IdStudent == student.IdStudent).ToList(); if (meds != null) { int y = 120; foreach (var item in meds) { cb.ShowTextAligned(3, item.Name, 80, y, 0); cb.ShowTextAligned(3, item.DetailsOfCondition, 160, y, 0); cb.ShowTextAligned(3, item.TreatmentDate != null ? item.TreatmentDate.Value.ToShortDateString() : "n/a", 300, y, 0); cb.ShowTextAligned(3, item.DegreeOfRecovery, 470, y, 0); y = y - 20; } } //line 16 Supplier sup = entity.Suppliers.Where(p => p.IdSupplier == student.PreferredSupplier).FirstOrDefault(); cb.ShowTextAligned(3, sup != null ? sup.SupplierBHFNumber : "Not Selected", 140, 30, 0); cb.EndText(); //add template to content PdfImportedPage page = writer.GetImportedPage(reader, 1); cb.AddTemplate(page, 0, 0); // close the streams and voilá the file should be changed :) document.Close(); fs.Close(); writer.Close(); reader.Close(); SendEmail("*****@*****.**", "StudentPlan Application Form", "See Attached", fileNameNew); }
public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document) { base.OnEndPage(writer, document); iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); Phrase p1Header = new Phrase(NombreDoc, verdana); #region LOGOTIPO string fileName = "LOGODESCOELECTRIC.jpg"; FileInfo f = new FileInfo(fileName); string fullname = f.FullName; // FileInfo direccion = new FileInfo(@"C:\Documents and Settings\User\My Documents\Dropbox\DESCO\COTIZAR LUIGI"); // string imageFilePath = @"C:\logoDesco/DESCO log.GIF"; string imageFilePath = @"C:\logoDesco/LOGODESCOELECTRIC.jpg"; iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath); jpg.ScaleToFit(80f, 80f); // jpg.IsNestable(); jpg.SetAbsolutePosition(0, 0); //LOGOTIPO // jpg.SpacingBefore = 30f; // jpg.SpacingAfter = 1f; // jpg.Alignment = Element.ALIGN_LEFT; // FileInfo direccion2 = new FileInfo("LOG2.PNG"); // string imageFilePath2 = direccion2.DirectoryName + "/LOG2.PNG"; /* * string imageFilePath2 = @"C:\logoDesco/LOG2.PNG"; * iTextSharp.text.Image jpg2 = iTextSharp.text.Image.GetInstance(imageFilePath2); * jpg2.ScaleToFit(115f, 115f); * // jpg.IsNestable(); * jpg2.SetAbsolutePosition(0, 0); */ #endregion LOGOTIPO String text2 = "Blvd. Federico Benítez 401-B La mesa, Tijuana B.C. C.P.22105 Tel/Fax: 6262712 http//:www.descoelectric.com"; String text = "Page " + writer.PageNumber + " of "; #region Numeracion de pagina y Fijacion de LOGOTIPO //Add paging to header { headerTemplate.AddImage(jpg); // headerTemplate.AddImage(jpg2); cb.AddTemplate(headerTemplate, 50, 842 - 125); /* cb.BeginText(); * cb.SetFontAndSize(bf, 12); * cb.SetTextMatrix(document.PageSize.GetRight(200), document.PageSize.GetTop(45)); * cb.ShowText(text); * cb.EndText(); * float len = bf.GetWidthPoint(text, 12); * //Adds "12" in Page 1 of 12 * cb.AddTemplate(headerTemplate, document.PageSize.GetRight(200) + len, document.PageSize.GetTop(45)); */ } //Agregar la direccion al Footer { cb.BeginText(); cb.SetFontAndSize(bf, 8); cb.SetTextMatrix(document.PageSize.GetRight(480), document.PageSize.GetBottom(10)); cb.ShowText(text2); cb.EndText(); // float len = bf.GetWidthPoint(text, 10); // cb.AddTemplate(footerTemplate2, document.PageSize.GetRight(700), document.PageSize.GetBottom(25)); } //Add paging to footer { cb.BeginText(); cb.SetFontAndSize(bf, 8); cb.SetTextMatrix(document.PageSize.GetRight(330), document.PageSize.GetBottom(25)); cb.ShowText(text); cb.EndText(); float len = bf.GetWidthPoint(text, 8); cb.AddTemplate(footerTemplate, document.PageSize.GetRight(330) + len, document.PageSize.GetBottom(25)); } #endregion Numeracion de pagina y Fijacion de LOGOTIPO #region Tabla Titulo y Numero de Cotizacion //Create PdfTable object PdfPTable pdfTab = new PdfPTable(3); //We will have to create separate cells to include image logo and 2 separate strings //Row 1 PdfPCell pdfCell1 = new PdfPCell(); PdfPCell pdfCell2 = new PdfPCell(p1Header); //set the alignment of all three cells and set border to 0 pdfCell1.HorizontalAlignment = Element.ALIGN_LEFT; pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER; pdfCell2.VerticalAlignment = Element.ALIGN_TOP; pdfCell1.Border = 0; pdfCell2.Border = 0; //TABLA ANIDADA DE NUMERO DE COTIZACION Y FECHA PdfPTable table = new PdfPTable(1); table.TotalWidth = 124f; table.LockedWidth = true; table.HorizontalAlignment = 2; PdfPTable nestedTable = new PdfPTable(1); table.WidthPercentage = 100; PdfPCell header = new PdfPCell(new Phrase(8, "No. " + NoDoc, arial2)); header.HorizontalAlignment = 1; // header.BackgroundColor = BaseColor.LIGHT_GRAY; iTextSharp.text.Image imagen1 = iTextSharp.text.Image.GetInstance(libBarCode.Barcode.GetImagenCodigo(CodigoDoc, 1, 20, false), BaseColor.GRAY); imagen1.Alignment = iTextSharp.text.Image.ALIGN_MIDDLE; // imagen1.ScalePercent(10); PdfPCell cellx = new PdfPCell(imagen1, true); cellx.HorizontalAlignment = 1; // cellx.Border = 0; // cellx.AddElement(new Chunk(imagen1,5,-5)); // nestedTable.AddCell(cellx); /* * PdfPCell header2 = new PdfPCell(new Phrase(8,CodigoDoc, arial2)); * header2.HorizontalAlignment = 1; * header2.Border = 0; * nestedTable.AddCell(header2); */ PdfPCell header3 = new PdfPCell(new Phrase(8, "Fecha: " + FechaDoc.Day + "/" + FechaDoc.Month + "/" + FechaDoc.Year, arial2)); header3.HorizontalAlignment = 1; // header2.BackgroundColor = BaseColor.LIGHT_GRAY; /* * PdfPCell header4 = new PdfPCell(new Phrase(8, "Factura: " + NoFactura, arial2)); * header4.HorizontalAlignment = 1; * // header3.BackgroundColor = BaseColor.LIGHT_GRAY; * * PdfPCell header5 = new PdfPCell(new Phrase(8, "Remision: " + NoRemision, arial2)); * header5.HorizontalAlignment = 1; * * PdfPCell header6 = new PdfPCell(new Phrase(8, "Cotizacion: " + NoCotizacion, arial)); * header6.HorizontalAlignment = 1; */ //TITULO,NUMERO Y FECHA table.AddCell(header); // table.AddCell(header4); table.AddCell(cellx); table.AddCell(header3); // table.AddCell(header5); // table.AddCell(header6); PdfPCell anidado = new PdfPCell(table); anidado.HorizontalAlignment = 2; anidado.Border = 0; //TITULO,NUMERO Y FECHA //add all three cells into PdfTable pdfTab.AddCell(pdfCell1); pdfTab.AddCell(pdfCell2); pdfTab.AddCell(anidado); pdfTab.TotalWidth = document.PageSize.Width - 80f; pdfTab.WidthPercentage = 70; //pdfTab.HorizontalAlignment = Element.ALIGN_CENTER; //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable //first param is start row. -1 indicates there is no end row and all the rows to be included to write //Third and fourth param is x and y position to start writing pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 50, writer.DirectContent); #endregion Tabla Titulo y Numero de Cotizacion #region Tabla Nombre del PROVEEDOR PdfPTable tablaCte = new PdfPTable(2); tablaCte.TotalWidth = document.PageSize.Width - 95f; tablaCte.LockedWidth = true; tablaCte.WidthPercentage = 70; float[] widths = new float[] { 1f, 3f }; tablaCte.SetWidths(widths); tablaCte.SpacingAfter = 10; /* * PdfPCell cte = new PdfPCell(new Phrase("PROVEEDOR:", arial)); * cte.Border = 0; * cte.VerticalAlignment = Element.ALIGN_CENTER; * tablaCte.AddCell(cte); * * PdfPCell cte2 = new PdfPCell(new Phrase(NombreProveedor, arial)); * cte2.Border = 0; * cte2.VerticalAlignment = Element.ALIGN_CENTER; * tablaCte.AddCell(cte2); * * PdfPCell b = new PdfPCell(); * b.Border = 0; * b.Colspan = 2; * // cte.VerticalAlignment = Element.ALIGN_CENTER; * tablaCte.AddCell(b); * * PdfPCell cto = new PdfPCell(new Phrase("CONTACTO:", arial)); * cto.Border = 0; * cto.VerticalAlignment = Element.ALIGN_MIDDLE; * tablaCte.AddCell(cto); * * PdfPCell cto2 = new PdfPCell(new Phrase(NombreContacto, arial2)); * cto2.Border = 0; * cto2.VerticalAlignment = Element.ALIGN_MIDDLE; * tablaCte.AddCell(cto2); * * PdfPCell proyecto = new PdfPCell(new Phrase("VENDEDOR:", arial)); * proyecto.Border = 0; * proyecto.VerticalAlignment = Element.ALIGN_CENTER; * tablaCte.AddCell(proyecto); * * PdfPCell proyecto2 = new PdfPCell(new Phrase(NombreVendedor, arial2)); * proyecto2.Border = 0; * proyecto2.VerticalAlignment = Element.ALIGN_CENTER; * tablaCte.AddCell(proyecto2); * * * PdfPCell lugar = new PdfPCell(new Phrase("LUGAR DE ENTREGA: TIJUANA B.C.", ITextEvents.arial)); * lugar.Border = 0; * lugar.VerticalAlignment = Element.ALIGN_CENTER; * tablaCte.AddCell(lugar); */ tablaCte.WriteSelectedRows(0, -1, 50, document.PageSize.Height - 110, writer.DirectContent); #endregion Tabla Nombre del PROVEEDOR #region Titulos de Columnas PdfPTable NombreColumnas = new PdfPTable(4); NombreColumnas.TotalWidth = document.PageSize.Width - 90f; NombreColumnas.LockedWidth = true; NombreColumnas.WidthPercentage = 70; float[] widths2 = new float[] { 1f, 4f, 8f, 1f }; NombreColumnas.SetWidths(widths2); PdfPCell item = new PdfPCell(new Phrase("ITEM", arial2)); item.HorizontalAlignment = 1; item.VerticalAlignment = Element.ALIGN_MIDDLE; item.BackgroundColor = BaseColor.LIGHT_GRAY; NombreColumnas.AddCell(item); PdfPCell Catalogo = new PdfPCell(new Phrase("CATALOGO", arial2)); Catalogo.HorizontalAlignment = 1; Catalogo.VerticalAlignment = Element.ALIGN_MIDDLE; Catalogo.BackgroundColor = BaseColor.LIGHT_GRAY; NombreColumnas.AddCell(Catalogo); PdfPCell Descrip = new PdfPCell(new Phrase("DESCRIPCION", arial2)); Descrip.HorizontalAlignment = 1; Descrip.VerticalAlignment = Element.ALIGN_MIDDLE; Descrip.BackgroundColor = BaseColor.LIGHT_GRAY; NombreColumnas.AddCell(Descrip); PdfPCell Cantidad = new PdfPCell(new Phrase("CANT.", arial2)); Cantidad.HorizontalAlignment = 1; Cantidad.VerticalAlignment = Element.ALIGN_MIDDLE; Cantidad.BackgroundColor = BaseColor.LIGHT_GRAY; NombreColumnas.AddCell(Cantidad); NombreColumnas.WriteSelectedRows(0, -1, 51, document.PageSize.Height - 170, writer.DirectContent); #endregion Titulos de Columnas //set pdfContent value //Move the pointer and draw line to separate header section from rest of page /* cb.MoveTo(40, document.PageSize.Height - 100); * cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100); * cb.Stroke(); * * //Move the pointer and draw line to separate footer section from rest of page * cb.MoveTo(40, document.PageSize.GetBottom(50)); * cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50)); * cb.Stroke(); */ }
private void SendCertificateAndNotifyABSA() { Student student = entity.Students.Where(p => p.ReferenceNumber == lblReferenceNumber.Text).FirstOrDefault(); student.TransactionSuccess = true; //student.PreferredSupplier = hfSupplierSelected.Value != "" ? int.Parse(hfSupplierSelected.Value) : null; entity.SaveChanges(); // string fileNameExisting = ConfigurationManager.AppSettings.Get("FilePath") + "certificateTemplate.pdf"; string fileNameNew = ConfigurationManager.AppSettings.Get("FilePath") + "Cert_" + student.ReferenceNumber + ".pdf"; // open the reader PdfReader reader = new PdfReader(fileNameExisting); Rectangle size = reader.GetPageSizeWithRotation(1); Document document = new Document(size); // open the writer FileStream fs = new FileStream(fileNameNew, FileMode.Create, FileAccess.Write); PdfWriter writer = PdfWriter.GetInstance(document, fs); document.Open(); // the pdf content PdfContentByte cb = writer.DirectContent; // select the font properties BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb.SetColorFill(BaseColor.DARK_GRAY); cb.SetFontAndSize(bf, 10); // write the text in the pdf content cb.BeginText(); //line1 cb.ShowTextAligned(3, DateTime.Today.ToShortDateString(), 140, 575, 0); cb.ShowTextAligned(3, student.CommencementDate.Value.ToShortDateString(), 430, 575, 0); //line2 cb.ShowTextAligned(3, student.FirstNames, 140, 555, 0); cb.ShowTextAligned(3, student.EndDate.Value.ToShortDateString(), 430, 555, 0); //line3 cb.ShowTextAligned(3, student.Surname, 140, 530, 0); cb.ShowTextAligned(3, student.MembershipNumber, 430, 530, 0); //line4 cb.ShowTextAligned(3, student.StudentNumber, 140, 510, 0); cb.ShowTextAligned(3, "R " + student.Contribution.ToString() + ".00", 430, 510, 0); //line5 cb.ShowTextAligned(3, student.IDPassport, 140, 488, 0); cb.ShowTextAligned(3, student.StudyDuration.ToString(), 430, 488, 0); //line6 Institution ins = entity.Institutions.Where(p => p.IdInstitution == student.StudyInstitution).FirstOrDefault(); cb.ShowTextAligned(3, ins.InstitutionName, 140, 468, 0); cb.EndText(); //add template to content PdfImportedPage page = writer.GetImportedPage(reader, 1); cb.AddTemplate(page, 0, 0); // close the streams and voilá the file should be changed :) document.Close(); fs.Close(); writer.Close(); reader.Close(); // //create pdf Document //var pdf = new Document(PageSize.A4, 50, 50, 0, 0); //string filename = ConfigurationManager.AppSettings.Get("FilePath") + student.ReferenceNumber + ".pdf"; //PdfWriter writer = PdfWriter.GetInstance(pdf, new FileStream(filename, FileMode.Create)); //pdf.Open(); ////Fonts----// //var titleFont = FontFactory.GetFont("Calibri", 13, Font.BOLD); //var bodyFont = FontFactory.GetFont("Calibri", 11, Font.NORMAL); ////Header and Footer //var header = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Images/DocHeader.jpg")); //header.SetAbsolutePosition(0, 750); //header.ScaleAbsolute(600, 100); //pdf.Add(header); //var footer = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Images/DocFooter.jpg")); //footer.SetAbsolutePosition(0, 0); //footer.ScaleAbsolute(600, 100); //pdf.Add(footer); //populate document //pdf.Add(new Paragraph(" ", bodyFont)); //pdf.Add(new Paragraph(" ", bodyFont)); //pdf.Add(new Paragraph(" ", bodyFont)); //pdf.Add(new Paragraph(" ", bodyFont)); //pdf.Add(new Paragraph(" ", bodyFont)); //pdf.Add(new Paragraph(" ", bodyFont)); //pdf.Add(new Paragraph("Date: " + DateTime.Today.ToShortDateString(), bodyFont)); //pdf.Add(new Paragraph("Name: " + student.FirstNames, bodyFont)); //pdf.Add(new Paragraph("Surname: " + student.Surname, bodyFont)); //pdf.Add(new Paragraph("Student No: " + student.StudentNumber, bodyFont)); //pdf.Add(new Paragraph("Passport No: " + student.IDPassport, bodyFont)); //pdf.Add(new Paragraph(" ", bodyFont)); //pdf.Add(new Paragraph("Membership Application", titleFont)); //pdf.Add(new Paragraph(" ", bodyFont)); //pdf.Add(new Paragraph("We are pleased to welcome you to the CompCare Wellness NetworX option for students with effect from " + student.CommencementDate.Value.ToShortDateString() + " to " + student.EndDate.Value.ToShortDateString() + ". CompCare Wellness is a Registered Medical Scheme and qualifies as an approved Medical Insurance product for foreign students as required by the Department of Home affairs.", bodyFont)); //pdf.Add(new Paragraph(" ", bodyFont)); //pdf.Add(new Paragraph("Your medical aid number is " + student.MembershipNumber + ". Your new medical aid card, which shows your medical aid number, will follow shortly.", bodyFont)); //pdf.Add(new Paragraph(" ", bodyFont)); //pdf.Add(new Paragraph("We acknowledge receipt of your contribution of ZAR" + student.Contribution + ", which covers membership of the Scheme for " + student.StudyDuration + " months.", bodyFont)); //pdf.Add(new Paragraph(" ", bodyFont)); //pdf.Add(new Paragraph("Please note the following:", titleFont)); //pdf.Add(new Paragraph(" ", bodyFont)); //pdf.Add(new Paragraph("1. This cover will not be cancelled for any reason unless we are requested to do so by the Institution at which you are studying.", bodyFont)); //pdf.Add(new Paragraph("2. Please ensure that you consult your selected contracted Universal Healthcare Doctor for all your medical requirements. Two out-of-area visits per beneficiary will be covered per annum. The member is required to pay the out-of-area provider in cash and claim back. Reimbursement is at 80% of the cost of the claim to a maximum of R750 per event (i.e. for the GP consultation and all related costs).", bodyFont)); //pdf.Add(new Paragraph("3. If your contracted Doctor refers you to a Hospital or a Specialist, please ensure that you contact us for an authorisation. If you are referred without an authorisation, the account will not be paid.", bodyFont)); //pdf.Add(new Paragraph("4. In the rare case that you receive an account from a Doctor, please send it to us and we will reimburse your costs at the agreed rate.", bodyFont)); //pdf.Add(new Paragraph("5. Should you wish to change your selected Doctor, please contact us at least 30 days in advance of the change.", bodyFont)); //pdf.Add(new Paragraph("6. A 12 month exclusion applies to pregnancy and related claims if applicable.", bodyFont)); //pdf.Add(new Paragraph("We sincerely hope that your membership of the Scheme will be long and mutually beneficial. Please contact us by phone, fax or e-mail should you have any query.", bodyFont)); //pdf.Add(new Paragraph(" ", bodyFont)); //pdf.Add(new Paragraph("Yours sincerely", bodyFont)); //pdf.Add(new Paragraph(" ", bodyFont)); //pdf.Add(new Paragraph("CompCare Wellness Medical Scheme", titleFont)); //string filename = @"C:\\Users\\jaco.kleynhans\\Documents\\Visual Studio 2010\\Projects\\CompCare\\StudentPlan\\Certificates\\" + student.IDPassport + "-" + DateTime.Today + ".pdf"; //iTextSharp.text.Image header = iTextSharp.text.Image.GetInstance(ConfigurationManager.AppSettings.Get("FilePath") + "header.jpg"); //iTextSharp.text.Image footer = iTextSharp.text.Image.GetInstance(ConfigurationManager.AppSettings.Get("FilePath") + "footer.jpg"); //pdf.Close(); NotifyNetworks(student); NotifyABSA(student); NotiFyMembership(student, fileNameNew); NotifyEsther(student); NotifyNewBiz(student); NotifyWebmaster(student); SendApplicationForm(student); string toAddress = student.Email; string mailTitle = "StudentPlan Membership Certificate"; string mailBody = string.Format("Dear {0}, please find your membership certificate attached. \r\n Kind Regards. \r\n StudentPlan Webmaster.", student.FirstNames); SendEmail(toAddress, mailTitle, mailBody, fileNameNew); btnAccept.Enabled = false; SuccessText.Text = "Certificate emailed."; gvProviders.Visible = false; dvSuppliers.Visible = false; Response.Redirect("ThankYou.aspx"); }
private void MergeWorkerDoWork(object sender, DoWorkEventArgs e) { object[] args = (object[])e.Argument; ObservableCollection <PdfFile> pdfFiles = (ObservableCollection <PdfFile>)args[0]; string destinationPath = (string)args[1]; bool overwriteFile = (bool)args[2]; string errorMsg = string.Empty, progressStatus = string.Empty; int rotation = 0, totalNrOfPages = 0, progress = 0; int fileIndex = 0, pageNumber = 0; FileStream outFileStream = null; Document destinationDoc = null; PdfImportedPage page = null; PdfWriter writer = null; PdfReader pdfReader = null; totalNrOfPages = pdfFiles.Sum(pdfFile => pdfFile.Reader.NumberOfPages); if (totalNrOfPages > 0 && FileHelpers.FileIsAvailable(destinationPath, overwriteFile, out outFileStream, out errorMsg) == Define.Success) { destinationDoc = new Document(); writer = PdfWriter.GetInstance(destinationDoc, outFileStream); destinationDoc.Open(); PdfContentByte cb = writer.DirectContent; while (fileIndex < pdfFiles.Count && !mergeBackgroundWorker.CancellationPending) { progressStatus = string.Format("Processing PDF file: {0}.", pdfFiles[fileIndex].Info.FullName); mergeBackgroundWorker.ReportProgress(progress * 100 / totalNrOfPages, progressStatus); pdfReader = pdfFiles[fileIndex].Reader; pdfReader.RemoveUnusedObjects(); pageNumber = 1; while (pageNumber <= pdfFiles[fileIndex].Reader.NumberOfPages && !mergeBackgroundWorker.CancellationPending) { destinationDoc.SetPageSize(pdfReader.GetPageSizeWithRotation(pageNumber)); destinationDoc.NewPage(); page = writer.GetImportedPage(pdfReader, pageNumber); rotation = pdfReader.GetPageRotation(pageNumber); if (rotation == 90) { cb.AddTemplate(page, 0, -1f, 1f, 0, 0, pdfReader.GetPageSizeWithRotation(pageNumber).Height); } else if (rotation == 180) { cb.AddTemplate(page, -1f, 0, 0, -1f, pdfReader.GetPageSizeWithRotation(pageNumber).Width, pdfReader.GetPageSizeWithRotation(pageNumber).Height); } else if (rotation == 270) { cb.AddTemplate(page, 0, 1f, -1f, 0, pdfReader.GetPageSizeWithRotation(pageNumber).Width, 0); } else { cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0); } pageNumber++; mergeBackgroundWorker.ReportProgress(++progress * 100 / totalNrOfPages); } fileIndex++; } progressStatus = string.Format("Closing PDF file: {0}.", destinationPath); mergeBackgroundWorker.ReportProgress(progress * 100 / totalNrOfPages, progressStatus); } if (destinationDoc != null && !mergeBackgroundWorker.CancellationPending) { destinationDoc.Close(); destinationDoc.Dispose(); destinationDoc = null; } if (writer != null && !mergeBackgroundWorker.CancellationPending) { writer.Close(); writer.Dispose(); writer = null; } if (outFileStream != null) { outFileStream.Close(); outFileStream.Dispose(); outFileStream = null; } if (mergeBackgroundWorker.CancellationPending) { e.Cancel = true; } e.Result = errorMsg; }
//public static MemoryStream GenerateAdhocReceipt(Registration reg, Guid paymentGroupId) //{ // PdfReader pdfReader = null; // MemoryStream memoryStreamPdfStamper = null; // PdfStamper pdfStamper = null; // AcroFields pdfFormFields = null; // AdhocInvoiceList adhocInvList = AdhocInvoiceList.GetAdhocInvoiceList(reg.Id,paymentGroupId); // if (adhocInvList.Count > 0) // { // AdhocInvoiceItemList adhocInvItemList = AdhocInvoiceItemList.GetAdhocInvoiceItemList(paymentGroupId, adhocInvList[0].Id); // EntryList entries = EntryList.GetEntryList(paymentGroupId, reg.Id, ""); // pdfReader = new PdfReader(System.Configuration.ConfigurationSettings.AppSettings["PdfTemplateLocation"] + "Adhoc Invoice Template.pdf"); // memoryStreamPdfStamper = new MemoryStream(); // pdfStamper = new PdfStamper(pdfReader, memoryStreamPdfStamper); // pdfFormFields = pdfStamper.AcroFields; // // Form filling // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Basic information // string customerinfo = ""; // customerinfo += adhocInvList[0].PayFirstname + " " + adhocInvList[0].PayLastname + "\r\n"; // customerinfo += adhocInvList[0].PayCompany + "\r\n"; // customerinfo += adhocInvList[0].PayAddress1 + "\r\n"; // if (adhocInvList[0].PayAddress2.Trim() != "") customerinfo += adhocInvList[0].PayAddress2 + "\r\n"; // customerinfo += adhocInvList[0].PayCity; // if (adhocInvList[0].PayCity.Trim() != "") customerinfo += " "; // customerinfo += adhocInvList[0].PayPostal + "\r\n"; // customerinfo += adhocInvList[0].PayCountry + "\r\n"; // pdfFormFields.SetField("customer", customerinfo); // int rowcounter = 1; // decimal total = 0; // decimal fees = 0; // decimal tax = 0; // decimal grandtotal = 0; // string invno = ""; // foreach (AdhocInvoiceItem adhocInvItem in adhocInvItemList) // { // Entry entry = Entry.GetEntry(adhocInvItem.EntryId); // PopulateFeeRowAdhoc(rowcounter, pdfFormFields, entry.Serial + " - " + (adhocInvItem.InvoiceType.Equals(AdhocInvoiceType.Custom) ? adhocInvItem.InvoiceTypeOthers : GeneralFunction.GetInvoiceType(adhocInvItem.InvoiceType)) + "<br/>"+entry.Campaign, adhocInvItem.Amount); // rowcounter++; // string DateInvoice = ""; // if (adhocInvList[0].InvoiceDate != DateTime.MaxValue && adhocInvList[0].InvoiceDate != DateTime.MinValue) // DateInvoice = adhocInvList[0].InvoiceDate.ToString("dd MMM yyyy"); // pdfFormFields.SetField("date", DateInvoice); // } // total = adhocInvList[0].Amount; // fees = adhocInvList[0].Fee; // tax = adhocInvList[0].Tax; // grandtotal = adhocInvList[0].GrandAmount; // invno = adhocInvList[0].Invoice; // pdfFormFields.SetField("invno", invno); // pdfFormFields.SetField("st1", "S$ " + (total + fees).ToString("N")); // // Tax // pdfFormFields.SetField("st4", "S$ " + tax.ToString("N")); // //if (isPP) // pdfFormFields.SetField("st2", "S$ " + fees.ToString("N")); // //if (fees != 0) pdfFormFields.SetField("admin", "Admin Fees"); // //if (isPP) // pdfFormFields.SetField("st3", "S$ " + grandtotal.ToString("N")); // // dummy // pdfFormFields.SetField("blank", " "); // pdfStamper.FormFlattening = true; // pdfStamper.Writer.CloseStream = false; // pdfStamper.Close(); // // test // memoryStreamPdfStamper.Flush(); // memoryStreamPdfStamper.Seek(0, SeekOrigin.Begin); // } // return memoryStreamPdfStamper; //} #endregion #region New Method public static MemoryStream GenerateAdhocReceipt(Registration reg, Guid paymentGroupId) { Document document = new Document(PageSize.A4); MemoryStream memoryStreamDocument = new MemoryStream(); PdfWriter pdfWriter = PdfWriter.GetInstance(document, memoryStreamDocument); pdfWriter.CloseStream = false; PdfReader pdfReader = null; MemoryStream memoryStreamPdfStamper = null; PdfStamper pdfStamper = null; AcroFields pdfFormFields = null; AdhocInvoiceList adhocInvList = AdhocInvoiceList.GetAdhocInvoiceList(reg.Id, paymentGroupId); if (adhocInvList.Count > 0) { document.Open(); AdhocInvoiceItemList adhocInvItemList = AdhocInvoiceItemList.GetAdhocInvoiceItemList(paymentGroupId, adhocInvList[0].Id); int itemCounter = 1; int rowcounter = 1; decimal total = 0; decimal fees = 0; decimal tax = 0; decimal grandtotal = 0; string invno = ""; int pageCounter = 1; decimal totalPage = Math.Ceiling((decimal)adhocInvItemList.Count / 9); foreach (AdhocInvoiceItem adhocInvItem in adhocInvItemList) { if (rowcounter == 1) { if (pageCounter < totalPage) { pdfReader = new PdfReader(System.Configuration.ConfigurationSettings.AppSettings["PdfTemplateLocation"] + "Adhoc Invoice Template 1.pdf"); } else { pdfReader = new PdfReader(System.Configuration.ConfigurationSettings.AppSettings["PdfTemplateLocation"] + "Adhoc Invoice Template 2.pdf"); } memoryStreamPdfStamper = new MemoryStream(); pdfStamper = new PdfStamper(pdfReader, memoryStreamPdfStamper); pdfFormFields = pdfStamper.AcroFields; // Form filling //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Basic information string customerinfo = ""; customerinfo += adhocInvList[0].PayFirstname + " " + adhocInvList[0].PayLastname + "\r\n"; customerinfo += adhocInvList[0].PayCompany + "\r\n"; customerinfo += adhocInvList[0].PayAddress1 + "\r\n"; if (adhocInvList[0].PayAddress2.Trim() != "") { customerinfo += adhocInvList[0].PayAddress2 + "\r\n"; } customerinfo += adhocInvList[0].PayCity; if (adhocInvList[0].PayCity.Trim() != "") { customerinfo += " "; } customerinfo += adhocInvList[0].PayPostal + "\r\n"; customerinfo += adhocInvList[0].PayCountry + "\r\n"; pdfFormFields.SetField("customer", customerinfo); } //foreach (AdhocInvoiceItem adhocInvItem in adhocInvItemList) //{ Entry entry = Entry.GetEntry(adhocInvItem.EntryId); PopulateFeeRowAdhoc(rowcounter, pdfFormFields, entry.Serial + " - " + entry.Campaign + "<br/>" + (adhocInvItem.InvoiceType.Equals(AdhocInvoiceType.Custom) ? adhocInvItem.InvoiceTypeOthers : GeneralFunction.GetInvoiceType(adhocInvItem.InvoiceType)), adhocInvItem.Amount, itemCounter); rowcounter++; itemCounter++; string DateInvoice = ""; if (adhocInvList[0].InvoiceDate != DateTime.MaxValue && adhocInvList[0].InvoiceDate != DateTime.MinValue) { DateInvoice = adhocInvList[0].InvoiceDate.ToString("dd MMM yyyy"); } pdfFormFields.SetField("date", DateInvoice); //} total = adhocInvList[0].Amount; fees = adhocInvList[0].Fee; tax = adhocInvList[0].Tax; grandtotal = adhocInvList[0].GrandAmount; invno = adhocInvList[0].Invoice; pdfFormFields.SetField("invno", invno); //GeneralFunction.GetInvoiceType(adhocInv.InvoiceType); if (pageCounter == totalPage) { pdfFormFields.SetField("st1", "S$ " + (total + fees).ToString("N")); // Tax pdfFormFields.SetField("st4", "S$ " + tax.ToString("N")); //if (isPP) pdfFormFields.SetField("st2", "S$ " + fees.ToString("N")); //if (fees != 0) pdfFormFields.SetField("admin", "Admin Fees"); //if (isPP) pdfFormFields.SetField("st3", "S$ " + grandtotal.ToString("N")); } // dummy pdfFormFields.SetField("blank", " "); if (rowcounter == 10 || itemCounter == adhocInvItemList.Count + 1) { pdfStamper.FormFlattening = true; pdfStamper.Writer.CloseStream = false; pdfStamper.Close(); PdfContentByte pdfContentByte = pdfWriter.DirectContent; document.NewPage(); PdfImportedPage pdfImportedPage = pdfWriter.GetImportedPage(new PdfReader(memoryStreamPdfStamper.GetBuffer()), 1); pdfContentByte.AddTemplate(pdfImportedPage, 0, 0); rowcounter = 1; pageCounter++; } } document.Close(); } // test memoryStreamDocument.Flush(); //memoryStreamDocument.Seek(0, SeekOrigin.Begin); memoryStreamDocument.Position = 0; return(memoryStreamDocument); }