public void SaveBatch(string fileName, MemoryStream document, FileTypes fileType) { // 1. Check to see we need to create the file if (!File.Exists(fileName)) { File.WriteAllBytes(fileName, document.ToArray()); } // 2. If it exists, append the new file else { using (var existingDocument = new Doc()) { using (var fs = File.Open(fileName, FileMode.Open)) { existingDocument.Read(fs); using (var docToAppend = new Doc()) { document.Position = 0; docToAppend.Read(document); existingDocument.Append(docToAppend); } } existingDocument.Save(fileName); } } }
/// <summary> /// Merges PDF Documents /// </summary> /// <param name="documentsToMergeList">Paths of Docuemnts to Merge</param> /// <param name="outputLocation">Output Location</param> /// <param name="pageSizeEnum"></param> /// <returns>Total Numnber of Pages</returns> public int MergeDocuments(List <string> documentsToMergeList, string outputLocation, PdfPageSizeEnum pageSizeEnum) { try { using (Doc doc1 = new Doc()) { //set the page size of the entire document doc1.MediaBox.String = pageSizeEnum.ToString(); foreach (var documentToMerge in documentsToMergeList) { Doc doc2 = new Doc(); doc2.Read(documentToMerge); doc1.Append(doc2); doc2.Dispose(); } doc1.Form.MakeFieldsUnique(Guid.NewGuid().ToString()); doc1.Encryption.CanEdit = false; doc1.Encryption.CanChange = false; doc1.Encryption.CanFillForms = false; doc1.Save(outputLocation); return(doc1.PageCount); } } catch (Exception e) { var documents = string.Join(", ", (from l in documentsToMergeList select l)); //this.Log().Error(string.Format("Error converting the following documents {0} to ouput location {1}", documents, outputLocation), e); //Throw the stack trace with it. throw; } }
public void Merge(string parentFile, IEnumerable <string> filesToMerge) { var outputPdfDoc = new Doc(); if (File.Exists(parentFile)) { outputPdfDoc.Read(parentFile); } try { foreach (string file in filesToMerge) { var inputPdfDoc = new Doc(); inputPdfDoc.Read(file); outputPdfDoc.Append(inputPdfDoc); inputPdfDoc.Clear(); inputPdfDoc.Dispose(); } outputPdfDoc.Save(parentFile); } finally { outputPdfDoc.Clear(); outputPdfDoc.Dispose(); } }
/// <summary> /// Merges PDF Documents and also creates new documents for the string provided and merges them /// </summary> /// <param name="documentsToMergeList">Existng documents that need to be merged</param> /// <param name="documentsToCreateAndMergeList">List of String Data which need to be added to a new document that is merged</param> /// <param name="outputLocation">output location where the nerge file gets saved</param> /// <returns></returns> public int MergeDocuments(List <string> documentsToMergeList, List <string> documentsToCreateAndMergeList, string outputLocation) { try { using (Doc doc1 = new Doc()) { //Merge existing documents foreach (var documentToMerge in documentsToMergeList) { Doc doc2 = new Doc(); doc2.Read(documentToMerge); doc1.Append(doc2); doc2.Dispose(); } //Create New documents and Merge foreach (var documentToCreateAndMerge in documentsToCreateAndMergeList) { using (Doc doc2 = new Doc()) { doc2.FontSize = 40; doc2.AddText(documentToCreateAndMerge); doc1.Append(doc2); } } doc1.Form.MakeFieldsUnique(Guid.NewGuid().ToString()); doc1.Encryption.CanEdit = false; doc1.Encryption.CanChange = false; doc1.Encryption.CanFillForms = false; doc1.Save(outputLocation); return(doc1.PageCount); } } catch (Exception e) { var documents = string.Join(", ", (from l in documentsToMergeList select l)); //this.Log().Error(string.Format("Error converting the following documents {0} to ouput location {1}", documents, outputLocation), e); //Throw the stack trace with it. throw; } }
public int MergeDocuments(List <string> documentsToMergeList, List <string> documentsToCreateAndMergeList, string outputLocation, PdfPageSizeEnum pageSizeEnum) { try { using (Doc doc1 = new Doc()) { //set the page size of the entire document doc1.MediaBox.String = pageSizeEnum.ToString(); //Merge existing documents foreach (var documentToMerge in documentsToMergeList) { Doc doc2 = new Doc(); doc2.Read(documentToMerge); //add each page of the plan to the doc2. It will add it as A4 size for (int i = 1; i <= doc2.PageCount; i++) { doc1.Page = doc1.AddPage(); doc1.AddImageDoc(doc2, i, null); doc1.FrameRect(); } doc2.Dispose(); } //Create New documents and Merge foreach (var documentToCreateAndMerge in documentsToCreateAndMergeList) { using (Doc doc2 = new Doc()) { doc2.FontSize = 40; doc2.AddText(documentToCreateAndMerge); doc1.Append(doc2); } } doc1.Form.MakeFieldsUnique(Guid.NewGuid().ToString()); doc1.Encryption.CanEdit = false; doc1.Encryption.CanChange = false; doc1.Encryption.CanFillForms = false; doc1.Save(outputLocation); return(doc1.PageCount); } } catch (Exception e) { var documents = string.Join(", ", (from l in documentsToMergeList select l)); //this.Log().Error(string.Format("Error converting the following documents {0} to ouput location {1}", documents, outputLocation), e); //Throw the stack trace with it. throw; } }
/// <summary> /// Merges Document1 into Document 2 /// </summary> /// <param name="document1"></param> /// <param name="document2"></param> /// <returns></returns> public int MergeDocuments(string document1, string document2) { try { using (Doc docMerge = new Doc()) { Doc doc1 = new Doc(); doc1.Read(document1); Doc doc2 = new Doc(); doc2.Read(document2); docMerge.Append(doc1); docMerge.Append(doc2); doc1.Dispose(); doc2.Dispose(); docMerge.Form.MakeFieldsUnique(Guid.NewGuid().ToString()); docMerge.Encryption.CanEdit = false; docMerge.Encryption.CanChange = false; docMerge.Encryption.CanFillForms = false; docMerge.Save(document2); return(docMerge.PageCount); } } catch (Exception e) { //this.Log().Error(string.Format("Error converting a document to PDF: {0} to {1}", document1, document2), e); //Throw the stack trace with it. throw; } }
private void MicrosoftOfficeWordToPdfConversion(string originalFileName, string targetFileName) { var xr = new XReadOptions { ReadModule = ReadModuleType.MSOffice }; using (var docPdf = new Doc()) { var doc1 = new Doc(); doc1.Read(originalFileName, xr); docPdf.Append(doc1); doc1.Dispose(); docPdf.Save(targetFileName); } }
private static void AppendPdf(Doc finalReport, string sourceDocPath) { if (!string.IsNullOrEmpty(sourceDocPath)) { var sourceDocPdfDoc = new Doc(); try { sourceDocPdfDoc.Read(sourceDocPath); finalReport.Append(sourceDocPdfDoc); } finally { sourceDocPdfDoc.Clear(); sourceDocPdfDoc.Dispose(); } } }
public Doc GetMergePdf(string html) { var arlFormsHTML = html.Split(new List <string> { "@jump@" }.ToArray(), StringSplitOptions.RemoveEmptyEntries); var pdfAllDocs = new Doc(); foreach (var item in arlFormsHTML) { var pdfAppend = new Doc(); pdfAppend = CreatePDFFromString(item); pdfAllDocs.Append(pdfAppend); pdfAppend.Dispose(); } return(pdfAllDocs); }
public MemoryStream GetDocumentsStream(List <FileDocumentDTO> docs, bool mergeDocs) { // List of final docs for non-preview var mergedPdf = new List <Doc>(); // Single doc for preview var previewPdf = new Doc(); foreach (var doc in docs.OrderBy(x => x.OrderInsidePdf)) { #region " SINGLE HTML FILE " if (doc.DocumentType == (int)TemplatePdfType.PdfAttachment) { var htmlDoc = GetMergePdf(doc.ReplacedHtml); if (mergeDocs) { previewPdf.Append(htmlDoc); } else { mergedPdf.Add(htmlDoc); } } #endregion } var responseStream = new MemoryStream(); if (mergeDocs) { mergedPdf.Add(previewPdf); } foreach (var d in mergedPdf) { using (var ms = new MemoryStream()) { d.Save(ms); responseStream = new MemoryStream(ms.ToArray()); } } return(responseStream); }
public byte[] CombinePages(IEnumerable <byte[]> pages) { byte[] returnBytes; using (var doc = new Doc()) { foreach (var page in pages) { using (var tempDoc = new Doc()) { tempDoc.Read(page); doc.Append(tempDoc); } } returnBytes = doc.GetData(); } return(returnBytes); }
/// <summary> /// Merges the documentsToMergeList into the mergeIntoDocument /// </summary> /// <param name="documentsToMergeList"></param> /// <param name="mergeIntoDocument"></param> /// <returns></returns> public int MergeDocumentsIntoDocument(List <string> documentsToMergeList, string mergeIntoDocument) { try { using (Doc docMerge = new Doc()) { foreach (var documentToMerge in documentsToMergeList) { Doc doc = new Doc(); doc.Read(documentToMerge); docMerge.Append(doc); doc.Dispose(); } if (new Files.FileHelper().Exits(mergeIntoDocument)) { Doc docMergeInto = new Doc(); docMergeInto.Read(mergeIntoDocument); } docMerge.Form.MakeFieldsUnique(Guid.NewGuid().ToString()); docMerge.Encryption.CanEdit = false; docMerge.Encryption.CanChange = false; docMerge.Encryption.CanFillForms = false; docMerge.Save(mergeIntoDocument); return(docMerge.PageCount); } } catch (Exception e) { var documents = string.Join(", ", (from l in documentsToMergeList select l)); //this.Log().Error(string.Format("Error converting the following documents {0} to {1}", documents, mergeIntoDocument), e); //Throw the stack trace with it. throw; } }
public static ResponseVal ConvertHmlToPDF(string QuoteISN, string StaffISN) { Globals.WriteLog("[ConvertHmlToPDF_CreateFile]: ----------Begin----------"); Globals.WriteLog("[ConvertHmlToPDF_CreateFile]: QuoteISN: " + QuoteISN); Globals.WriteLog("[ConvertHmlToPDF_CreateFile]: StaffISN: " + StaffISN); ResponseVal resVal = new ResponseVal(); var result = -1; //bool rsCheck = XSettings.InstallLicense("X/VKS08wmMtAun4hGNvFONzmS/QQY7hZ9Z2488LHIg8X5nu5Qx7dYsZhez00hWZRXd5Xim0uoXp3ifxwDtAusQ0lPTnPXR1401Y="); //bool rsCheck = XSettings.InstallLicense("XeJREBodo/8B4nxZb63WaYOgeuQZPdtypqn27rLhKmkRz3CDGnvCaco3Dn5c5nQFBw=="); //bool rsCheck = XSettings.InstallLicense("XeJREBodo/8B7XFQaf2CPdzyKuccPdtypszj/8HiXH0n+nieP1jmdZIuAHpU7kIFBw=="); //bool rsCheck = XSettings.InstallLicense("X/VKS0cNn5FipytaG9r2LN6gO9YNAb8f0JfhndPDLmJ14X+2ABmFVcU9cz81hwBrU4M7olk+wz9WgdFFKeN5mjkhfR3iZgJkr1Y="); bool rsCheck = XSettings.InstallLicense(Functions.GetConfig_CS("AbcPdfLicense")); if (!rsCheck) { resVal.Code = -1; resVal.Msg = "Invalid Websupergoo license."; return(resVal); } var ds = Globals.DB.ExecuteQuery(string.Format("select MemberISN from Vw_SolarQuote where QuoteISN={0}", Functions.ConvertObjectToInt(QuoteISN))); if (Functions.IsEmpty(ds)) { resVal.Code = -1; resVal.Data = null; resVal.Msg = "QuoteISN is missing"; Globals.WriteLog("[ConvertHmlToPDF_CreateFile]: Msg: " + resVal.Msg); Globals.WriteLog("[ConvertHmlToPDF_CreateFile]: ----------End----------"); return(resVal); } var row = ds.Tables[0].Rows[0]; var MemberISN = row["MemberISN"].ToString(); string url = string.Format("{0}/Proposal.aspx?isn={1}&staffisn={2}", Functions.GetConfig_CS("AdminURL").TrimEnd('/'), QuoteISN, StaffISN); Globals.WriteLog("[ConvertHmlToPDF_CreateFile] -- url: " + url); string Temp = Functions.GetConfig_CS("TemporaryDir"); string outputPath = HttpContext.Current.Server.MapPath("~/OutputFiles/Pdf"); string sFileName = ""; string sFullPathTemp = ""; #region Create PDF try { Doc pages = new Doc(); try { Doc doc = new Doc(); //doc.Rect.Inset(30, 10); //doc.HtmlOptions.Engine = EngineType.MSHtml; //doc.HtmlOptions.Engine = EngineType.Chrome; //doc.HtmlOptions.Engine = EngineType.MSHtml; //doc.SetInfo(0, "RenderDelay", "500"); //doc.SetInfo(0, "OneStageRender", 0); doc.HtmlOptions.FontEmbed = true; doc.HtmlOptions.FontSubstitute = false; doc.HtmlOptions.FontProtection = false; doc.HtmlOptions.BrowserWidth = 1200; doc.HtmlOptions.PageCacheClear(); doc.HtmlOptions.UseScript = true; //doc.HtmlOptions.OnLoadScript = "(function(){window.ABCpdf_go = false; setTimeout(function(){window.ABCpdf_go = true;}, 3000);})();"; // Render after 3 seconds //doc.HtmlOptions.OnLoadScript = " (function(){" // + " window.external.ABCpdf_RenderWait();" // + " setTimeout(function(){ " // + " window.external.ABCpdf_RenderComplete(); }, 5000);" // + "})();"; //doc.SetInfo(0, "RenderDelay", "5000"); //doc.SetInfo(0, "OneStageRender", 0); //Render after 3 seconds //doc.HtmlOptions.OnLoadScript = "(function(){" // + " window.ABCpdf_go = false;" // + " setTimeout(function(){ window.ABCpdf_go = true; }, 10000);" // + "})();"; doc.Page = doc.AddPage(); int theID; theID = doc.AddImageUrl(url); while (true) { doc.FrameRect(); // add a black border if (!doc.Chainable(theID)) { break; } doc.Page = doc.AddPage(); theID = doc.AddImageToChain(theID); System.Threading.Thread.Sleep(500); } //doc.Rect.String = "100 50 500 150"; //for (int i = 1; i <= doc.PageCount; i++) //{ // doc.PageNumber = i; // doc.AddText("Page " + i.ToString()); // //doc.FrameRect(); //} pages.Append(doc); } catch (Exception ex2) { resVal.Code = -1; resVal.Data = null; resVal.Msg = ex2.Message; Globals.WriteLog("[ConvertHmlToPDF_CreateFile] - Exception: " + ex2.Message); Globals.WriteLog("[ConvertHmlToPDF_CreateFile]: ----------End----------"); return(resVal); } if (!System.IO.File.Exists(Temp)) { System.IO.Directory.CreateDirectory(Temp); } Globals.WriteLog("[ConvertHmlToPDF_CreateFile] Temp: " + Temp); sFileName = "Proposal_" + DateTime.Now.Ticks.ToString() + ".pdf"; sFullPathTemp = Path.Combine(Temp, sFileName); pages.Save(sFullPathTemp); pages.Clear(); string sDocName = "Proposal_" + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Year + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second; result = (int)Globals.DB.ExecuteStoredProc("xp_debtext_documenttask_insupd", new string[] { "DocumentISN", "docFileName", "docName", "docType", "docPublic", "MemberISN" }, new object[] { 0, sFileName, sDocName, "Proposal", 1, MemberISN }); var sPathFileDoc = Path.Combine(Functions.GetConfig_CS("FilesDir"), GetDocumentsPath(result, null)); if (!System.IO.File.Exists(sPathFileDoc)) { System.IO.Directory.CreateDirectory(sPathFileDoc); } var sFileSave = Path.Combine(sPathFileDoc, sFileName); File.Copy(sFullPathTemp, sFileSave); //File.Delete(sFullPathTemp); resVal.Code = 1; resVal.Data = result; resVal.Msg = "Success"; Globals.WriteLog("[ConvertHmlToPDF_CreateFile] sFullPathTemp: " + sFullPathTemp); Globals.WriteLog("[ConvertHmlToPDF_CreateFile] sPathFileDoc: " + sFileSave); Globals.WriteLog("[ConvertHmlToPDF_CreateFile] sFileName: " + sFileName); Globals.WriteLog("[ConvertHmlToPDF_CreateFile] DocumentISN: " + result); } catch (Exception ex) { resVal.Code = -1; resVal.Data = null; resVal.Msg = ex.Message; Globals.WriteLog("[ConvertHmlToPDF_CreateFile] -- Exception: " + ex.Message); } Globals.WriteLog("[ConvertHmlToPDF_CreateFile]: ----------End----------"); #endregion #region old // string fileName = DateTime.Now.Ticks + ".pdf"; // string pathFileName = Path.Combine(Functions.GetConfig_CS("TemporaryDir"), fileName); // string ContentHtml = ReadFromFile(pathFileHtml); // //StringBuilder sb = new StringBuilder(); // //sb.Append(ContentHtml); // //var css = ContentHtml.Substring(ContentHtml.IndexOf("<style>") + 7, ContentHtml.IndexOf("</style>") - 7 - ContentHtml.IndexOf("<style>")); //// var js = ContentHtml.Substring(ContentHtml.IndexOf("<script>") + 8, ContentHtml.IndexOf("</script>") - 8 - ContentHtml.IndexOf("<script>")); // StringReader sr = new StringReader(ContentHtml); // //StringWriter sw = new StringWriter(); // //HtmlTextWriter hw = new HtmlTextWriter(sw); // //hw.Write(ContentHtml); // Document pdfDoc = new Document(PageSize.A4); // //HTMLWorker htmlparser = new HTMLWorker(pdfDoc); // using (MemoryStream memoryStream = new MemoryStream()) // { // PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream); // pdfDoc.Open(); // //htmlparser.Parse(new StringReader(sw.ToString())); // ////HTMLWorker.ParseToList(sr, new StyleSheet()); // //pdfDoc.Close(); // //StyleSheet ss = new StyleSheet(); // //ArrayList list = HTMLWorker.ParseToList(new StringReader(ContentHtml), ss); // //foreach (IElement e in list) // //{ // // pdfDoc.Add(e); // // // //using (TextReader sReader = new StringReader(ContentHtml.ToString())) // //{ // // ArrayList list = HTMLWorker.ParseToList(sReader, new StyleSheet()); // // foreach (IElement elm in list) // // { // // pdfDoc.Add(elm); // // } // //} // //pdfDoc.HtmlStyleClass = ContentHtml; // //pdfDoc.JavaScript_onLoad = ContentHtml; // //htmlparser.Parse(sr); // // step 5 // //Image img = Image.GetInstance(ContentHtml); // //pdfDoc.Add(img); // //writer.AddJavaScript(ContentHtml); // iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr); // //using (var srHtml = new StringReader(ContentHtml)) // //{ // // //Parse the HTML // // iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, srHtml); // //} // //using (var msCss = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_css))) // //{ // // using (var msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(ContentHtml))) // // { // // Parse the HTML // // iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, msHtml, msCss); // // } // //} // pdfDoc.Close(); // byte[] bytes = memoryStream.ToArray(); // //BinaryFormatter bf = new BinaryFormatter(); // //MemoryStream ms = new MemoryStream(); // //bf.Serialize(ms, ContentHtml); // //bytes = ms.ToArray(); // pathFileName = pathFileName + ".pdf"; // System.IO.File.WriteAllBytes(pathFileName, bytes); // memoryStream.Close(); // File.Copy(Path.Combine(Functions.GetConfig_CS("TemporaryDir"), fileName + ".pdf"), Path.Combine(Functions.GetConfig_CS("FilesConvertPdf"), fileName + ".pdf"), true); // resVal.Code = 1; // resVal.Data = pathFileName; // resVal.Msg = "Success"; // } #endregion return(resVal); }
public void GeneratePdfForHaf(string pageurl, string fileSavePath, string corporateSurveyPdf = "", string basicBiometricFile = "", string focAttestationFile = "", string corporateCheckListPdf = "", string annualComprehensiveExamPdf = "", string memberInformationProfilePdf = "") { var finalReport = new Doc(); try { finalReport.Rect.Inset(40, 70); //pdfDoc.Rect. finalReport.MediaBox.String = PaperSize; finalReport.Rect.String = finalReport.MediaBox.String; finalReport.Page = finalReport.AddPage(); finalReport.HtmlOptions.PageCachePurge(); finalReport.HtmlOptions.Timeout = 90000; if (AllowLoadingJavascriptbeforePdfGenerate) { finalReport.HtmlOptions.UseScript = true; } int imageToChain = finalReport.AddImageUrl(pageurl, true, 950, true); while (true) { if (!finalReport.Chainable(imageToChain)) { break; } finalReport.Page = finalReport.AddPage(); imageToChain = finalReport.AddImageToChain(imageToChain); } for (int pageNumber = 1; pageNumber <= finalReport.PageCount; pageNumber++) { finalReport.PageNumber = pageNumber; //Flatten page finalReport.Flatten(); } if (!string.IsNullOrEmpty(basicBiometricFile)) { var inputPdfDoc = new Doc(); try { inputPdfDoc.Read(basicBiometricFile); finalReport.Append(inputPdfDoc); } finally { inputPdfDoc.Clear(); inputPdfDoc.Dispose(); } } if (!string.IsNullOrEmpty(corporateSurveyPdf)) { var inputPdfDoc = new Doc(); try { inputPdfDoc.Read(corporateSurveyPdf); finalReport.Append(inputPdfDoc); } finally { inputPdfDoc.Clear(); inputPdfDoc.Dispose(); } } if (!string.IsNullOrEmpty(focAttestationFile)) { var inputPdfDoc = new Doc(); try { inputPdfDoc.Read(focAttestationFile); finalReport.Append(inputPdfDoc); } finally { inputPdfDoc.Clear(); inputPdfDoc.Dispose(); } } if (!string.IsNullOrEmpty(corporateCheckListPdf)) { var inputPdfDoc = new Doc(); try { inputPdfDoc.Read(corporateCheckListPdf); finalReport.Append(inputPdfDoc); } finally { inputPdfDoc.Clear(); inputPdfDoc.Dispose(); } } if (!string.IsNullOrEmpty(annualComprehensiveExamPdf)) { var inputPdfDoc = new Doc(); try { inputPdfDoc.Read(annualComprehensiveExamPdf); finalReport.Append(inputPdfDoc); } finally { inputPdfDoc.Clear(); inputPdfDoc.Dispose(); } } if (!string.IsNullOrEmpty(memberInformationProfilePdf)) { var inputPdfDoc = new Doc(); try { inputPdfDoc.Read(memberInformationProfilePdf); finalReport.Append(inputPdfDoc); } finally { inputPdfDoc.Clear(); inputPdfDoc.Dispose(); } } finalReport.Save(fileSavePath); } catch (Exception exception) { throw exception; } finally { finalReport.Clear(); finalReport.Dispose(); } }
public void GeneratePdf(string pageurl, string fileSavePath, bool showFooterText = false, string footerText = "", string coverSheetPages = "", string customizedLetter = "", string contentpages = "", string kynFile = "", string bloodLetter = "", string doctorLetter = "", string corporateFluffLetter = "", bool isPpCustomer = false, string awvTestResult = "", bool isPcpReport = false, bool generatePcpLetter = false, string scannedDocumentsPdf = "", string eawvPdfReport = "", string focAttestation = "", string attestationForm = "", bool hasSectionToDisplay = true, string mammogram = "", string ifobt = "", string urineMicroalbumin = "", string participantLetter = "", string chlamydia = "", string awvBoneMass = "", string osteoporosis = "", string quantaFloAbi = "", string hkyn = "", string mybioCheckAssessment = "", string memberLetter = "", string greenFormAttestation = "", string dpn = "") { var finalReport = new Doc(); int prePrintedCount = 0; var beforFinalReportDoc = new Doc(); try { if (coverSheetPages != "") { var participantLetterDoc = new Doc(); var doctorLetterDoc = new Doc(); var customizedLetterDoc = new Doc(); var contentpagesDoc = new Doc(); var eawvPdfDoc = new Doc(); var memberLetterDoc = new Doc(); var greenFormAttestationDoc = new Doc(); try { //Cover Sheet beforFinalReportDoc.Read(coverSheetPages); if (!string.IsNullOrWhiteSpace(greenFormAttestation)) { greenFormAttestationDoc.Read(greenFormAttestation); beforFinalReportDoc.Append(greenFormAttestationDoc); } //Member Letter if (!string.IsNullOrEmpty(memberLetter)) { memberLetterDoc.Read(memberLetter); beforFinalReportDoc.Append(memberLetterDoc); } if (!string.IsNullOrEmpty(participantLetter)) { participantLetterDoc.Read(participantLetter); beforFinalReportDoc.Append(participantLetterDoc); } //Doctor letter if (!string.IsNullOrEmpty(doctorLetter)) { doctorLetterDoc.Read(doctorLetter); beforFinalReportDoc.Append(doctorLetterDoc); } //Customized Letter Hospital Partner no default letter if (!string.IsNullOrEmpty(customizedLetter)) { customizedLetterDoc.Read(customizedLetter); beforFinalReportDoc.Append(customizedLetterDoc); } if (!string.IsNullOrEmpty(contentpages)) { contentpagesDoc.Read(contentpages); beforFinalReportDoc.Append(contentpagesDoc); } if (!string.IsNullOrEmpty(eawvPdfReport)) { eawvPdfDoc.Read(eawvPdfReport); beforFinalReportDoc.Append(eawvPdfDoc); } prePrintedCount = beforFinalReportDoc.PageCount; } catch (Exception exception) { throw exception; } finally { participantLetterDoc.Clear(); participantLetterDoc.Dispose(); doctorLetterDoc.Clear(); doctorLetterDoc.Dispose(); customizedLetterDoc.Clear(); customizedLetterDoc.Dispose(); contentpagesDoc.Clear(); contentpagesDoc.Dispose(); eawvPdfDoc.Clear(); eawvPdfDoc.Dispose(); memberLetterDoc.Clear(); memberLetterDoc.Dispose(); greenFormAttestationDoc.Clear(); greenFormAttestationDoc.Dispose(); } } if (hasSectionToDisplay) { finalReport.Rect.Inset(40, 70); //pdfDoc.Rect. finalReport.MediaBox.String = PaperSize; finalReport.Rect.String = finalReport.MediaBox.String; finalReport.Page = finalReport.AddPage(); finalReport.HtmlOptions.PageCachePurge(); finalReport.HtmlOptions.Timeout = 90000; if (AllowLoadingJavascriptbeforePdfGenerate) { finalReport.HtmlOptions.UseScript = true; } int imageToChain = finalReport.AddImageUrl(pageurl, true, 950, true); while (true) { if (!finalReport.Chainable(imageToChain)) { break; } finalReport.Page = finalReport.AddPage(); imageToChain = finalReport.AddImageToChain(imageToChain); } footerText = string.IsNullOrEmpty(footerText) ? string.Empty : footerText + " | "; int pageCount = finalReport.PageCount + prePrintedCount; for (int pageNumber = 1; pageNumber <= finalReport.PageCount; pageNumber++) { finalReport.PageNumber = pageNumber; if (showFooterText) { int pNum = pageNumber + prePrintedCount; string txt = footerText + "Page: " + pNum + " of " + pageCount; finalReport.Color.String = "0 0 0"; //Dark grey text finalReport.TextStyle.VPos = 0.98; finalReport.TextStyle.HPos = (pageNumber % 2) == 0 ? 0.10 : 0.80; finalReport.AddFont("Arial"); //Add the page number finalReport.AddText(txt); //Add a line above page number finalReport.AddLine(21, 40, 590, 40); } //Flatten page finalReport.Flatten(); } } if (!string.IsNullOrEmpty(kynFile)) { var inputPdfDoc = new Doc(); try { inputPdfDoc.Read(kynFile); finalReport.Append(inputPdfDoc); } finally { inputPdfDoc.Clear(); inputPdfDoc.Dispose(); } } AppendPdf(finalReport, hkyn); if (!string.IsNullOrEmpty(bloodLetter)) { var inputPdfDoc = new Doc(); try { inputPdfDoc.Read(bloodLetter); finalReport.Append(inputPdfDoc); } finally { inputPdfDoc.Clear(); inputPdfDoc.Dispose(); } } if (!string.IsNullOrEmpty(corporateFluffLetter)) { var inputPdfDoc = new Doc(); try { inputPdfDoc.Read(corporateFluffLetter); finalReport.Append(inputPdfDoc); } finally { inputPdfDoc.Clear(); inputPdfDoc.Dispose(); } } if (!string.IsNullOrEmpty(awvTestResult)) { var inputPdfDoc = new Doc(); try { inputPdfDoc.Read(awvTestResult); finalReport.Append(inputPdfDoc); } finally { inputPdfDoc.Clear(); inputPdfDoc.Dispose(); } } if (!string.IsNullOrEmpty(scannedDocumentsPdf)) { var inputScannedPdfDoc = new Doc(); try { inputScannedPdfDoc.Read(scannedDocumentsPdf); finalReport.Append(inputScannedPdfDoc); } finally { inputScannedPdfDoc.Clear(); inputScannedPdfDoc.Dispose(); } } AppendPdf(finalReport, focAttestation); AppendPdf(finalReport, attestationForm); AppendPdf(finalReport, mammogram); AppendPdf(finalReport, ifobt); AppendPdf(finalReport, urineMicroalbumin); AppendPdf(finalReport, chlamydia); AppendPdf(finalReport, awvBoneMass); AppendPdf(finalReport, osteoporosis); AppendPdf(finalReport, quantaFloAbi); AppendPdf(finalReport, mybioCheckAssessment); AppendPdf(finalReport, dpn); if (coverSheetPages != "") { try { beforFinalReportDoc.Append(finalReport); beforFinalReportDoc.Save(fileSavePath); } catch (Exception exception) { throw exception; } } else { finalReport.Save(fileSavePath); } } catch (Exception exception) { throw exception; } finally { finalReport.Clear(); finalReport.Dispose(); beforFinalReportDoc.Clear(); beforFinalReportDoc.Dispose(); } }
private Doc CreateTestDoc(int assessmentID, List<AssessmentPrintBatchHelper> assessmentPrintBatchHelpers, Doc doc, string imagesUrl,bool isAdminInst=false) { /* Modified to add uploaded document */ int userID = SessionObject.LoggedInUser.Page; var assessmentInfo = Assessment.GetConfigurationInformation(assessmentID, userID); var contentType = assessmentInfo.ContentType; bool stringCompareResult = contentType.Equals(_externalTestType, StringComparison.OrdinalIgnoreCase); bool noDataFlag = true; if (!contentType.Equals(_externalTestType, StringComparison.OrdinalIgnoreCase)) // Is this an External Test { doc = Assessment.RenderAssessmentToPdf_Batch(assessmentID, assessmentPrintBatchHelpers, imagesUrl, isAdminInst); // Not an External Document noDataFlag = false; } else { foreach (var assessmentPrintBatchHelper in assessmentPrintBatchHelpers) //Test Can have multiple Forms (Example: Form 201, Form 101, form 301, etc.) { DataTable tbl = Assessment.GetDocs(assessmentID); string tempFile = string.Empty; string AnswerKeyTempFile = tbl.Rows[0][_answerKeyFile].ToString(); string[] attachmentTypes = { _assementFile, _reviewerFile, _answerKeyFile }; //rename formNames Attacment types /** Print Uploaded Assessment file **/ foreach (string attachmentType in attachmentTypes) { if (!string.IsNullOrEmpty(tbl.Rows[0][attachmentType].ToString())) { tempFile = tbl.Rows[0][attachmentType].ToString(); using (Doc externalDoc = new Doc()) { int docCount = 0; switch (attachmentType) { case _assementFile: docCount = assessmentPrintBatchHelper.AssessmentCount; break; case _reviewerFile: docCount = assessmentPrintBatchHelper.AssessmentCount; break; case _answerKeyFile: docCount = assessmentPrintBatchHelper.AnswerKeyCount; break; } externalDoc.Read(Server.MapPath("~/upload/" + tempFile)); for (int j = 0; j < docCount; j++) { doc.Append(externalDoc); noDataFlag = false; } } } } //Ashley Reeves said that the Answer Key must Print if there is no enternal file loaded - Reference TFS Bug 1350 if (string.IsNullOrEmpty(AnswerKeyTempFile) && assessmentPrintBatchHelper.AnswerKeyCount > 0) { Doc answerKeyDoc = new Doc(); answerKeyDoc = Assessment.RenderAssessmentToPdf(assessmentID, assessmentPrintBatchHelper.FormID, PdfRenderSettings.PrintTypes.AnswerKey, isAdminInst); //answerKeyDoc = Assessment.RenderAssessmentAnswerKeyToPdf_Batch(assessmentID, assessmentPrintBatchHelpers); // Not an External Document for (int j = 0; j < assessmentPrintBatchHelper.AnswerKeyCount; j++) { doc.Append(answerKeyDoc); noDataFlag = false; } answerKeyDoc.Dispose(); } //1-30-2014 Bug 13579:Print on External Assessment with Rubric should print Rubric and not blank pdf if (assessmentPrintBatchHelper.RubricCount > 0) { Doc RubricDoc = new Doc(); RubricDoc = Assessment.RenderAssessmentToPdf(assessmentID, assessmentPrintBatchHelper.FormID, PdfRenderSettings.PrintTypes.Rubric, isAdminInst); for (int j = 0; j < assessmentPrintBatchHelper.RubricCount; j++) { doc.Append(RubricDoc); noDataFlag = false; } RubricDoc.Dispose(); } //END 1-30-2014 Bug 13579 } #region JavaScript //string scriptName = "MasterJavaScript"; //string myScriptName = "CustomMessage"; //if (noDataFlag && !ClientScript.IsClientScriptBlockRegistered(scriptName) && !ClientScript.IsClientScriptBlockRegistered(myScriptName)) //Verify script isn't already registered //{ // string masterJavaScriptText = string.Empty; // string filePath = Server.MapPath("~/Scripts/master.js"); // using (StreamReader MasterJavaScriptFile = new StreamReader(filePath)) // { // masterJavaScriptText = MasterJavaScriptFile.ReadToEnd(); // } // if (!string.IsNullOrEmpty(masterJavaScriptText)) // { // ClientScript.RegisterClientScriptBlock(this.GetType(), scriptName, masterJavaScriptText); // string myScript = "var confirmDialogText = 'There are no external test or answer sheets loaded. Please upload a test and/or answer sheet.';" + // "\n customDialog({ maximize: true, maxwidth: 300, maxheight: 100, resizable: false, title: 'No Uploaded Documents', content: confirmDialogText, dialog_style: 'confirm' }," + // "\n [{ title: 'OK', callback: cancelCallbackFunction }, { title: 'Cancel'}]);"; // ClientScript.RegisterStartupScript(this.GetType(), myScriptName, myScript,true); // } //} #endregion //JavaScript if (noDataFlag) doc = Assessment.NoExternalFiles(); // Prints if there are no external files to print } /** End of adding the uploaded document **/ return doc; }
/// <summary> /// Create an estimate body in html format, related to an Estimate. /// </summary> /// <param name="HTML">The HTML.</param> /// <param name="estimateid">estimate id.</param> /// <param name="theDoc">The doc.</param> /// <param name="printCustomerDetails">if set to <c>true</c> [print customer details].</param> /// <param name="promotiontypeid">The promotiontypeid.</param> /// <returns>Pdf document</returns> public Doc PrintEstimateBody(string pdftemplate, int estimateid, Doc theDoc) { StringBuilder sb = new StringBuilder(); StringBuilder tempdesc = new StringBuilder(); string tempStr = string.Empty; // Add the Disclaimer/Acknowledgements body text. Doc theDoc3 = new Doc(); theDoc3.MediaBox.SetRect(0, 0, 595, 600); theDoc3.Rect.String = "0 0 565 600"; theDoc3.Color.Color = System.Drawing.Color.Black; theDoc3.Font = theDoc3.AddFont(Common.PRINTPDF_DEFAULT_FONT); theDoc3.TextStyle.Size = Common.PRINTPDF_DISCLAIMER_FONTSIZE; theDoc3.TextStyle.Bold = false; theDoc3.Rect.Pin = 0; theDoc3.Rect.Position(20, 0); theDoc3.Rect.Width = 400; theDoc3.Rect.Height = 600; theDoc3.TextStyle.LeftMargin = 25; string disclaimer = Common.getDisclaimer(estimateRevisionId.ToString(), Session["OriginalLogOnState"].ToString(), estimateRevision_internalVersion, estimateRevision_disclaimer_version).Replace("$Token$", tempStr); disclaimer = disclaimer.Replace("$printdatetoken$", DateTime.Now.ToString("dd/MMM/yyyy")); disclaimer = disclaimer.Replace("$logoimagetoken$", Server.MapPath("~/images/metlog.jpg")); if (variationnumber == "--") { disclaimer = disclaimer.Replace("$DaysExtension$", " "); } else { disclaimer = disclaimer.Replace("$DaysExtension$", string.Format("EXTENSION OF TIME {0} DAYS (Due to the above variation)", extentiondays)); } // If QLD, then use a real deposit amount in the Agreement if (Session["OriginalLogOnStateID"] != null) { if (Session["OriginalLogOnStateID"].ToString() == "3") { DBConnection DBCon = new DBConnection(); SqlCommand Cmd = DBCon.ExecuteStoredProcedure("spw_checkIfContractDeposited"); Cmd.Parameters["@contractNo"].Value = BCContractnumber; DataSet ds = DBCon.SelectSqlStoredProcedure(Cmd); double amount = 0; if (ds != null && ds.Tables[0].Rows.Count > 0) { amount = double.Parse(ds.Tables[0].Rows[0]["DepositAmount"].ToString()); } if (amount > 0.00) { disclaimer = disclaimer.Replace("$DepositAmount$", "payment of " + String.Format("{0:C}", amount)); } else { disclaimer = disclaimer.Replace("$DepositAmount$", "payment as receipted"); } } } if (disclaimer.Trim() != "") { int docid = theDoc3.AddImageHtml(disclaimer); while (true) { if (!theDoc3.Chainable(docid)) { break; } theDoc3.Page = theDoc3.AddPage(); docid = theDoc3.AddImageToChain(docid); } } theDoc.Append(theDoc3); return(theDoc); }
public static string ConvertHtmlToPDF(string filePathHTML) { WriteLog("[ConvertHmlToPDF_CreateFile]: ----------Begin----------"); WriteLog("[ConvertHmlToPDF_CreateFile] filePathHTML: " + filePathHTML); string result = string.Empty; bool rsCheck = XSettings.InstallLicense("X/VKS08wmMtAun4hGNvFONzmS/QQY7hZ9Z2488LHIg8X5nu5Qx7dYsZhez00hWZRXd5Xim0uoXp3ifxwDtAusQ0lPTnPXR1401Y="); if (!rsCheck) { result = "Invalid Websupergoo license."; WriteLog("[ConvertHmlToPDF_CreateFile] result: " + result); return(null); } string FilesDir = Functions.GetAppConfigByKey("FileDir"); if (!System.IO.File.Exists(FilesDir)) { System.IO.Directory.CreateDirectory(FilesDir); } string fileName = "File_Convert_PDF" + DateTime.Now.Ticks.ToString() + ".pdf"; string fullPath = Path.Combine(FilesDir, fileName); WriteLog("[ConvertHmlToPDF_CreateFile] FilesDir: " + FilesDir); WriteLog("[ConvertHmlToPDF_CreateFile] fileName: " + fileName); WriteLog("[ConvertHmlToPDF_CreateFile] fullPath: " + fullPath); #region Create PDF try { Doc pages = new Doc(); try { Doc doc = new Doc(); //doc.Rect.Inset(30, 10); //doc.HtmlOptions.Engine = EngineType.MSHtml; //doc.HtmlOptions.Engine = EngineType.Chrome; doc.HtmlOptions.FontEmbed = true; doc.HtmlOptions.FontSubstitute = false; doc.HtmlOptions.FontProtection = false; doc.HtmlOptions.BrowserWidth = 1200; doc.HtmlOptions.PageCacheClear(); doc.HtmlOptions.UseScript = true; //doc.HtmlOptions.OnLoadScript = "(function(){window.ABCpdf_go = false; setTimeout(function(){window.ABCpdf_go = true;}, 3000);})();"; // Render after 3 seconds //doc.HtmlOptions.OnLoadScript = " (function(){" // + " window.external.ABCpdf_RenderWait();" // + " setTimeout(function(){ " // + " window.external.ABCpdf_RenderComplete(); }, 10000);" // + "})();"; //doc.SetInfo(0, "RenderDelay", "45000"); //doc.SetInfo(0, "OneStageRender", 0); //Render after 3 seconds //doc.HtmlOptions.OnLoadScript = "(function(){" // + " window.ABCpdf_go = false;" // + " setTimeout(function(){ window.ABCpdf_go = true; }, 10000);" // + "})();"; doc.Page = doc.AddPage(); int theID; theID = doc.AddImageUrl(filePathHTML); while (true) { doc.FrameRect(); // add a black border if (!doc.Chainable(theID)) { break; } doc.Page = doc.AddPage(); theID = doc.AddImageToChain(theID); System.Threading.Thread.Sleep(500); } //doc.Rect.String = "100 50 500 150"; //for (int i = 1; i <= doc.PageCount; i++) //{ // doc.PageNumber = i; // doc.AddText("Page " + i.ToString()); // //doc.FrameRect(); //} pages.Append(doc); } catch (Exception ex2) { result = ex2.Message; WriteLog("[ConvertHmlToPDF_CreateFile] - Exception: " + result); return(null); } pages.Save(fullPath); pages.Clear(); result = fullPath; WriteLog("[ConvertHmlToPDF_CreateFile]: ----------End----------"); return(result); } catch (Exception ex) { result = ex.Message; WriteLog("[ConvertHmlToPDF_CreateFile] -- Exception: " + result); return(null); } #endregion }