public static void CreatePdfFromHtml(string htmlFilePath) { var htmlFileInfo = new FileInfo(htmlFilePath); if (!htmlFileInfo.Exists) { throw new FileNotFoundException(htmlFileInfo.FullName); } Debug.Assert(htmlFileInfo.DirectoryName != null, "htmlFileInfo.DirectoryName != null"); var tmpPdfFileInfo = new FileInfo(Path.Combine(htmlFileInfo.DirectoryName, "tmp.pdf")); var pdfOutFileInfo = new FileInfo(GetPdfEquivalentPath(htmlFileInfo.FullName)); var gc = new GlobalConfig(); gc.SetImageQuality(100); gc.SetOutputDpi(96); gc.SetPaperSize(1024, 1123); var oc = new ObjectConfig(); oc.SetLoadImages(true); oc.SetAllowLocalContent(true); oc.SetPrintBackground(true); oc.SetZoomFactor(1.093); oc.SetPageUri(htmlFileInfo.FullName); if (tmpPdfFileInfo.Exists) { tmpPdfFileInfo.Delete(); } IPechkin pechkin = new SynchronizedPechkin(gc); pechkin.Error += (converter, text) => { Console.Out.WriteLine("error " + text); }; pechkin.Warning += (converter, text) => { Console.Out.WriteLine("warning " + text); }; using (var file = File.OpenWrite(tmpPdfFileInfo.FullName)) { var bytes = pechkin.Convert(oc); file.Write(bytes, 0, bytes.Length); } if (pdfOutFileInfo.Exists) { pdfOutFileInfo.Delete(); } CreateDirectories(pdfOutFileInfo.DirectoryName); tmpPdfFileInfo.MoveTo(pdfOutFileInfo.FullName); }
void OnTriggerExit2D(Collider2D other) { // taxi has passenger and drive over building Debug.Log("Exit " + other.name); if (_targetTagName == "building" && _peopleId != string.Empty && _pickupState == PickupState.Pick) { if (_peopleId == _objectConfig.ID.ToString()) { Debug.Log("pickup state: kick"); // kick passenger _pickupState = PickupState.Kick; } //StartCoroutine (countsetMessageBox(_pickupState)); } if (other.tag == "people" && _pickupState == PickupState.Empty) { Debug.Log("pickup state: Don't pick"); other.gameObject.GetComponent <ObjectConfig> ().Anim(); StartCoroutine(countsetMessageBox(_pickupState)); } //Out if (_objectConfig == other.GetComponent <ObjectConfig>()) { _objectConfig = null; } step = OnTriggeris.Exit; }
//// Update is called once per frame //void Update () { //} public void SetupObject(ObjectConfig _configData) { configData = _configData; //hp = configData.hp; FindWeakPoints(); SetupUI(); }
public void PechkinMultiConvert(string FilesDir) { //取得目標資料夾中所有符合條件的所有檔案 string[] FilePath = Directory.GetFiles(FilesDir, "*"); //開始逐檔將HTML轉PDF foreach (var i in FilePath) { Console.WriteLine("開始從" + i + "\n\r 產生:" + Path.GetFileNameWithoutExtension(i) + ".pdf"); var config = new GlobalConfig(); var pechkin = new SimplePechkin(config); ObjectConfig oc = new ObjectConfig(); oc.SetPrintBackground(true).SetLoadImages(true); string HTML = ""; //讀入html try { // Open the text file using a stream reader. using (StreamReader sr = new StreamReader(i)) { // Read the stream to a string, and write the string to the console. HTML = sr.ReadToEnd(); } } catch (Exception e) { Console.WriteLine("The file could not be read:"); Console.WriteLine(e.Message); } byte[] pdf = pechkin.Convert(oc, HTML); File.WriteAllBytes(FilesDir + @"\" + Path.GetFileNameWithoutExtension(i) + ".pdf", pdf); Console.WriteLine(Path.GetFileNameWithoutExtension(i) + ".pdf 轉換完成"); } }
public static ObjectConfig GetObjectConfig(string id) { ObjectConfig result = null; sConfigs.TryGetValue(id.ToLower(), out result); return(result); }
public FileStreamResult GeneraPDF(string Documento, string RIF, string Titulo, string URL) { // create global configuration object GlobalConfig gc = new GlobalConfig(); // set it up using fluent notation gc.SetMargins(new Margins(50, 50, 0, 0)) .SetDocumentTitle(Titulo) .SetPaperSize(PaperKind.Letter); //... etc // create converter IPechkin pechkin = new SynchronizedPechkin(gc); // create document configuration object ObjectConfig oc = new ObjectConfig(); // and set it up using fluent notation too oc.SetCreateExternalLinks(false) .SetFallbackEncoding(Encoding.ASCII) .SetLoadImages(true) .SetPageUri(URL.Replace("GeneraPDF", "")); //... etc // convert document byte[] pdfBuf = pechkin.Convert(oc); HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + Titulo + " " + Documento + ".pdf"); MemoryStream ms = new MemoryStream(pdfBuf); return(new FileStreamResult(ms, "application/pdf")); }
public void GenerateMemberList(List <Member> members, DateTime snapshot) { try { string input = File.ReadAllText(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + "\\Templates\\Html\\Template_Memberlist.htm"); string str1 = "Ledenlijst: " + snapshot.ToShortDateString(); this.FilePath = Path.GetTempPath() + ("tmp" + Util.Util.RandomString(10)) + ".pdf"; StringBuilder stringBuilder = new StringBuilder(); int num = 1; foreach (Member member in members) { stringBuilder.Append(num % 2 > 0 ? "<tr>" : "<tr class=\"alt\">"); stringBuilder.Append("<td>" + (object)num + "</td>"); stringBuilder.Append("<td>" + member.LastName + "</td>"); stringBuilder.Append("<td>" + member.FirstName + "</td>"); stringBuilder.Append("<td>" + member.ZipCode + "</td>"); stringBuilder.Append("<td>" + member.City + "</td>"); stringBuilder.Append("<td>" + member.Address + "</td>"); stringBuilder.Append("<td>" + member.Country + "</td>"); DateTime dateTime = member.BirthDate ?? new DateTime(); stringBuilder.Append("<td>" + dateTime.ToShortDateString() + "</td>"); stringBuilder.Append("<td>" + member.Email + "</td>"); stringBuilder.Append("<td>" + member.TelephoneNr + "</td>"); stringBuilder.Append("</tr>"); ++num; } string str2 = new Regex("\\[(\\w+)\\]", RegexOptions.Compiled).Replace(input, (MatchEvaluator)(match => new Dictionary <string, string>((IEqualityComparer <string>)StringComparer.OrdinalIgnoreCase) { { "Title", str1 }, { "ImagePath", Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + "\\Templates\\Html" }, { "MemberOverviewTableElements", stringBuilder.ToString() } }[match.Groups[1].Value])); GlobalConfig config = new GlobalConfig(); config.SetMargins(new Margins(70, 45, 70, 45)).SetPaperSize(PaperKind.A4Rotated); SimplePechkin simplePechkin = new SimplePechkin(config); ObjectConfig objectConfig = new ObjectConfig(); objectConfig.SetLoadImages(true); objectConfig.SetPrintBackground(true); objectConfig.SetZoomFactor(1.1); objectConfig.SetAllowLocalContent(true); ObjectConfig doc = objectConfig; string html = str2; File.WriteAllBytes(this.FilePath, simplePechkin.Convert(doc, html)); PdfReportService.logger.Info("Memberlist PDF created: " + this.FilePath); } catch (Exception ex) { PdfReportService.logger.Error("Could not create temporary PDF file:" + ex.Message); } }
public static void StringToPDF(string html, string fileName) { using (IPechkin pechkin = Factory.Create(new GlobalConfig())) { ObjectConfig oConfig = new ObjectConfig(); oConfig.SetMinFontSize(14); byte[] pdf = pechkin.Convert(oConfig, html); File.WriteAllBytes(fileName, pdf); } }
void OnTriggerStay2D(Collider2D other) { //Stay if ((_objectConfig == null && _pickupState == PickupState.Empty && other.tag == "people") || (_objectConfig == null && _pickupState == PickupState.Pick && other.tag == "building")) { _targetTagName = other.tag; _objectConfig = other.GetComponent <ObjectConfig> (); } step = OnTriggeris.Stay; }
//html to Pdf public static void HtmlToPdf(string filePath, string html, bool isOrientation = false) { if (string.IsNullOrEmpty(html)) { html = "Null"; } // 创建全局信息 GlobalConfig gc = new GlobalConfig(); gc.SetMargins(new Margins(50, 50, 60, 60)) .SetDocumentTitle("MarkWord") .SetPaperSize(PaperKind.A4) .SetPaperOrientation(isOrientation) .SetOutlineGeneration(true); //页面信息 ObjectConfig oc = new ObjectConfig(); oc.SetCreateExternalLinks(false) .SetFallbackEncoding(Encoding.UTF8) .SetLoadImages(true) .SetScreenMediaType(true) .SetPrintBackground(true); //.SetZoomFactor(1.5); var pechkin = new SimplePechkin(gc); pechkin.Finished += Pechkin_Finished; pechkin.Error += Pechkin_Error; pechkin.ProgressChanged += Pechkin_ProgressChanged; var buf = pechkin.Convert(oc, html); if (buf == null) { Common.ShowMessage("导出异常"); return; } try { string fn = filePath; //Path.GetTempFileName() + ".pdf"; FileStream fs = new FileStream(fn, FileMode.Create); fs.Write(buf, 0, buf.Length); fs.Close(); //Process myProcess = new Process(); //myProcess.StartInfo.FileName = fn; //myProcess.Start(); } catch { } }
void OnTriggerEnter2D(Collider2D other) { //In forpickup = counttime; if ((_objectConfig == null && _pickupState == PickupState.Empty && other.tag == "people") || (_objectConfig == null && _pickupState == PickupState.Pick && other.tag == "building")) { _targetTagName = other.tag; _objectConfig = other.GetComponent <ObjectConfig> (); } step = OnTriggeris.Enter; }
void CreateObject(int _objectIndex) { ObjectConfig objectConfig = levelConfig.objects[_objectIndex]; GameObject objectGO = Instantiate(Resources.Load <GameObject>(objectConfig.prefab)); currentObject = objectGO.GetComponent <DestroyableObject>(); currentObject.SetupObject(objectConfig); cameraController.RegisterDestroyableObject(currentObject.transform); if (characterController != null) { characterController.RegisterTargetObject(currentObject); } }
public ActionResult DownloadPdf2() { string url = "http://www.baidu.com/"; using (IPechkin pechkin = Factory.Create(new GlobalConfig())) { ObjectConfig oc = new ObjectConfig(); oc.SetPrintBackground(true); oc.SetLoadImages(true); oc.SetScreenMediaType(true); oc.SetPageUri(url); byte[] pdf = pechkin.Convert(oc); return(File(pdf, "application/pdf", "ExportPdf.pdf")); } }
public bool GeneratePDFFile() { GlobalConfig globalConfig = new GlobalConfig(); globalConfig.SetMargins(new Margins(100, 100, 100, 100)) .SetDocumentTitle("") .SetPaperSize(PaperKind.A4); IPechkin pechkin = new SynchronizedPechkin(globalConfig); ObjectConfig configuration = new ObjectConfig(); configuration .SetAllowLocalContent(true) .SetPageUri(pathToHTML) .SetPrintBackground(true) .SetScreenMediaType(true); byte[] pdfContent = pechkin.Convert(configuration); SaveFileDialog saveFileDialog = new SaveFileDialog { Filter = "PDF (*.pdf)|*.pdf", RestoreDirectory = true, Title = "Choose a location to save your report", FileName = "TaxInvoice" + metadata["FIRST_NAME"] + metadata["LAST_NAME"] + DateTime.Now.ToString("yyyyMMdd"), DefaultExt = "pdf", CheckPathExists = true, InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) }; if (saveFileDialog.ShowDialog() == DialogResult.OK) { if (SaveByteArrayToPDFFile(saveFileDialog.FileName, pdfContent)) { Process.Start(saveFileDialog.FileName); return(true); } else { return(false); } } else { return(false); } }
public ActionResult ExportDemo() { SynchronizedPechkin sc = new SynchronizedPechkin(new GlobalConfig() .SetMargins(new Margins() { Left = 0, Right = 0, Top = 0, Bottom = 0 })); //设置边距 ObjectConfig oc = new ObjectConfig(); oc.SetPrintBackground(true).SetRunJavascript(true).SetScreenMediaType(true) .SetLoadImages(true) .SetPageUri("http://drp.xiaoni.com/recommendcase/FindCaseDetail.aspx?findid=657"); byte[] buf = sc.Convert(oc); return(File(buf, "application/pdf", "download.pdf")); }
public void ExportPdf() { ObjectConfig doc = new ObjectConfig().SetPrintBackground(this.IncludeCssBackground); GlobalConfig globalConfig = new GlobalConfig(); globalConfig.SetDocumentTitle(this.DocumentTitle).SetOutlineGeneration(this.EnableOutlineGeneration).SetPaperOrientation(this._settings.IO_Pdf_LandscapeMode).SetMarginLeft(this._settings.IO_Pdf_MarginLeftInMillimeters).SetMarginTop(this._settings.IO_Pdf_MarginTopInMillimeters).SetMarginRight(this._settings.IO_Pdf_MarginRightInMillimeters).SetMarginBottom(this._settings.IO_Pdf_MarginBottomInMillimeters).SetPaperSize(this._settings.IO_Pdf_PaperSize); IPechkin pechkin = new SynchronizedPechkin(globalConfig); pechkin.Finished += new FinishEventHandler(this.OnFinished); try { byte[] bytes = pechkin.Convert(doc, this.HtmlContent); System.IO.File.WriteAllBytes(this.OutputFilename, bytes); } catch (System.Exception exception) { PdfExporter._logger.ErrorException("Error exporting PDF", exception); MessageBoxHelper.ShowErrorMessageBox(LocalizationProvider.GetLocalizedString("Error_PdfExportMessage", false, "MarkdownPadStrings"), LocalizationProvider.GetLocalizedString("Error_PdfExportTitle", false, "MarkdownPadStrings"), exception, ""); } }
private void SpawnObject(int x, int y, TmxObject tmxObject) { ObjectConfig objectConfig = ConfigManager.main.GetObjectConfig(tmxObject.Name); GameObject gameObject = Instantiate(objectConfig.Prefab); if (gameObject.tag == "Player") { PlayerCharacter player = gameObject.GetComponent <PlayerCharacter>(); playerCamera.Follow = player.transform; player.Init(); } if (gameObject.tag == "Enemy") { Enemy enemy = gameObject.GetComponent <Enemy>(); enemy.Init(); enemyNumber += 1; } gameObject.transform.position = new Vector2(x, y); gameObject.transform.SetParent(GameManager.main.WorldParent); }
private void SaveHtmlAsPdf(string fName, string html) { GlobalConfig cfg = new GlobalConfig(); SimplePechkin sp = new SimplePechkin(cfg); ObjectConfig oc = new ObjectConfig(); oc.SetCreateExternalLinks(true) .SetFallbackEncoding(Encoding.ASCII) .SetLoadImages(true) .SetAllowLocalContent(true) .SetPrintBackground(true); byte[] pdfBuf = sp.Convert(oc, "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><title></title></head><body>" + html + "</body></html>"); FileStream fs = new FileStream(fName, FileMode.Create, FileAccess.ReadWrite); foreach (var byteSymbol in pdfBuf) { fs.WriteByte(byteSymbol); } fs.Close(); }
public void CreateRoomList(IEnumerable <RoomViewModel> rooms) { var rlvm = new RoomListViewModel { Rooms = rooms }; var html = CreateRoomListHtml(rlvm); ObjectConfig oc = new ObjectConfig(); oc.SetPrintBackground(true); oc.SetAllowLocalContent(true); oc.SetScreenMediaType(true); oc.SetLoadImages(true); oc.Footer.SetFontSize(8); oc.Footer.SetRightText("Erstellt: " + DateTime.Now); var pdfBuf = new SynchronizedPechkin(new GlobalConfig()).Convert(oc, html); var _SD = new SaveFileDialog { Filter = "PDF File (*.pdf)|*.pdf", FileName = TranslationProvider.Translate("RoomList"), Title = TranslationProvider.Translate("SaveAs") }; if (_SD.ShowDialog() == DialogResult.OK) { try { File.WriteAllBytes(_SD.FileName, pdfBuf); Process.Start(_SD.FileName); } catch (IOException e) { MessageBox.Show(TranslationProvider.Translate("CantWriteFile")); } } }
private static void WritePdfFromHtml(string html, string outputFile, string documentTitle, string cssFile, string headerHtmlFile, string footerHtmlFile) { GlobalConfig gc = new GlobalConfig(); gc.SetPaperSize(System.Drawing.Printing.PaperKind.A4); gc.SetPaperOrientation(false); gc.SetDocumentTitle(documentTitle); SimplePechkin pechkin = new SimplePechkin(gc); ObjectConfig oc = new ObjectConfig(); oc.SetAllowLocalContent(true); oc.SetPrintBackground(true); if (!string.IsNullOrEmpty(cssFile)) { /// for some reason oc.SetUserStylesheetUri(new Uri(cssFile).AbsoluteUri) is not working, so although /// this looks hacky, it gets the job done html = @"<link href=""" + new Uri(cssFile).AbsoluteUri + @""" rel=""stylesheet"" type=""text/css"" />" + System.Environment.NewLine + html; } if (!string.IsNullOrEmpty(headerHtmlFile)) { oc.Header.SetHtmlContent(new Uri(headerHtmlFile).AbsoluteUri); } if (!string.IsNullOrEmpty(footerHtmlFile)) { oc.Footer.SetHtmlContent(new Uri(footerHtmlFile).AbsoluteUri); } try { System.IO.File.WriteAllBytes(outputFile, pechkin.Convert(oc, html)); } catch (System.IO.IOException) { Console.WriteLine("The PDF file you are writing to is likely already open/in use"); } }
private void Inital() { pechkinTool = new SynchronizedPechkin(new GlobalConfig() //pechkinTool = new SimplePechkin(new GlobalConfig() //.SetImageQuality(500) .SetLosslessCompression(false) .SetPaperSize(PaperKind.Tabloid)); config = new ObjectConfig().SetPrintBackground(true) //.SetProxyString(String.Concat(StaticStrings.ProxyIP, ":", StaticStrings.ProxyPort)) .SetAllowLocalContent(true) .SetCreateExternalLinks(false) .SetCreateForms(false) .SetCreateInternalLinks(false) .SetErrorHandlingType(ObjectConfig.ContentErrorHandlingType.Ignore).SetFallbackEncoding(Encoding.ASCII) .SetIntelligentShrinking(false) .SetRenderDelay(2000) .SetRunJavascript(true) .SetIncludeInOutline(true) .SetZoomFactor(1) .SetLoadImages(true); }
public void Create() { Comprobante oComprobante; string pathXML = @"E:\ASP NET\ApplicationXMLtoPDF\ApplicationXMLtoPDF\xml\archivoXML4.xml"; XmlSerializer oSerializer = new XmlSerializer(typeof(Comprobante)); using (StreamReader reader = new StreamReader(pathXML)) { oComprobante = (Comprobante)oSerializer.Deserialize(reader); foreach (var oComplemento in oComprobante.Complemento) { foreach (var oComplementoInterior in oComplemento.Any) { if (oComplementoInterior.Name.Contains("TimbreFiscalDigital")) { XmlSerializer oSerializerComplemento = new XmlSerializer(typeof(TimbreFiscalDigital)); using (var readerComplemento = new StringReader(oComplementoInterior.OuterXml)) { oComprobante.TimbreFiscalDigital = (TimbreFiscalDigital)oSerializerComplemento.Deserialize(readerComplemento); } } } } } //Paso 2 Aplicando Razor y haciendo HTML a PDF string path = Server.MapPath("~") + "/"; string pathHTMLTemp = path + "miHTML.html";//temporal string pathHTPlantilla = path + "plantilla.html"; string sHtml = GetStringOfFile(pathHTPlantilla); string resultHtml = ""; resultHtml = Razor.Parse(sHtml, oComprobante); //Creamos el archivo temporal File.WriteAllText(pathHTMLTemp, resultHtml); GlobalConfig gc = new GlobalConfig(); gc.SetMargins(new Margins(100, 100, 100, 100)) .SetDocumentTitle("Test document") .SetPaperSize(PaperKind.Letter); // Create converter IPechkin pechkin = new SynchronizedPechkin(gc); // Create document configuration object ObjectConfig configuration = new ObjectConfig(); string HTML_FILEPATH = pathHTMLTemp; // and set it up using fluent notation too configuration .SetAllowLocalContent(true) .SetPageUri(@"file:///" + HTML_FILEPATH); // Generate the PDF with the given configuration // The Convert method will return a Byte Array with the content of the PDF // You will need to use another method to save the PDF (mentioned on step #3) byte[] pdfContent = pechkin.Convert(configuration); ByteArrayToFile(path + "prueba.pdf", pdfContent); //eliminamos el archivo temporal File.Delete(pathHTMLTemp); }
public void GenerateCheckoutTicketOverview(CheckoutSheet sheet) { try { string input = File.ReadAllText(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + "\\Templates\\Html\\Template_Checkoutsheet_TicketOverview.htm"); DateTime dateTime = sheet.OpenTime ?? DateTime.Now; string str1 = "Ticketoverzicht: " + dateTime.ToShortDateString(); this.FilePath = Path.GetTempPath() + ("Ticketoverzicht " + dateTime.ToString("dd_MM_yyyy HH_mm")) + ".pdf"; StringBuilder stringBuilder1 = new StringBuilder(); foreach (Ticket ticket in (Collection <Ticket>)sheet.Tickets) { stringBuilder1.AppendLine("<table class=\"table3\">"); stringBuilder1.AppendLine("<tr>"); stringBuilder1.AppendLine("<td colspan=\"6\" class=\"ticketTitle\">Ticket #" + (object)ticket.Id + "</td>"); stringBuilder1.AppendLine("</tr>"); stringBuilder1.AppendLine("<tr>"); stringBuilder1.AppendLine("<td class=\"ticketPropertyTitles\" colspan=\"2\">Datum</td>"); stringBuilder1.AppendLine("<td class=\"ticketPropertyTitles\">Waarde EUR</td>"); stringBuilder1.AppendLine("<td class=\"ticketPropertyTitles\">Waarde Bonnen</td>"); stringBuilder1.AppendLine("<td class=\"ticketPropertyTitles\" colspan=\"2\">Aangemaakt door</td>"); stringBuilder1.AppendLine("</tr>"); stringBuilder1.AppendLine("<tr>"); stringBuilder1.AppendLine("<td class =\"ticketPropertyValues\" colspan=\"2\">" + (object)ticket.CreationTime + "</td>"); stringBuilder1.AppendLine("<td class=\"ticketPropertyValues\">" + ticket.TotalPrice.ToString("C") + "</td>"); stringBuilder1.AppendLine("<td class=\"ticketPropertyValues\">" + (object)ticket.TotalCoins + "</td>"); stringBuilder1.AppendLine("<td class=\"ticketPropertyValues\" colspan=\"2\">" + ticket.CreatedBy.Fullname + "</td>"); stringBuilder1.AppendLine("</tr>"); stringBuilder1.AppendLine("<tr>"); stringBuilder1.AppendLine("<td colspan=\"6\"> </td>"); stringBuilder1.AppendLine("</tr>"); stringBuilder1.AppendLine("<tr>"); stringBuilder1.AppendLine(" <td colspan=\"6\" class=\"productsTitle\">Producten</td>"); stringBuilder1.AppendLine("</tr>"); stringBuilder1.AppendLine("<tr>"); stringBuilder1.AppendLine("<td class=\"productsPropertyTitles\">Naam</td>"); stringBuilder1.AppendLine("<td class =\"productsPropertyTitles\">Hoeveelheid</td>"); stringBuilder1.AppendLine("<td class=\"productsPropertyTitles\">Stukprijs EUR</td>"); stringBuilder1.AppendLine("<td class=\"productsPropertyTitles\">Stukprijs Bonnen</td>"); stringBuilder1.AppendLine("<td class=\"productsPropertyTitles\">Subtotaal EUR</td>"); stringBuilder1.AppendLine("<td class=\"productsPropertyTitles\">Subtotaal Bonnen</td>"); stringBuilder1.AppendLine("</tr>"); foreach (TicketLine ticketLine in (Collection <TicketLine>)ticket.TicketLines) { stringBuilder1.AppendLine("<tr>"); stringBuilder1.AppendLine("<td class =\"productsPropertyValues\">" + ticketLine.Product.Name + "</td>"); stringBuilder1.AppendLine("<td class =\"productsPropertyValues\">" + (object)ticketLine.Amount + "</td>"); StringBuilder stringBuilder2 = stringBuilder1; double num = ticketLine.UnitPrice; string str2 = "<td class =\"productsPropertyValues\">" + num.ToString("C") + "</td>"; stringBuilder2.AppendLine(str2); stringBuilder1.AppendLine("<td class =\"productsPropertyValues\">" + (object)ticketLine.UnitPriceCoins + "</td>"); StringBuilder stringBuilder3 = stringBuilder1; num = ticketLine.LinePriceIncl; string str3 = "<td class =\"productsPropertyValues\">" + num.ToString("C") + "</td>"; stringBuilder3.AppendLine(str3); stringBuilder1.AppendLine("<td class =\"productsPropertyValues\">" + (object)ticketLine.LinePriceCoins + "</td>"); stringBuilder1.AppendLine("</tr>"); } stringBuilder1.AppendLine("<tr>"); stringBuilder1.AppendLine("<td colspan=\"6\"> </td>"); stringBuilder1.AppendLine("</tr>"); stringBuilder1.AppendLine("<tr>"); stringBuilder1.AppendLine("<td colspan=\"6\" class=\"transactionsTitle\">Transacties</td>"); stringBuilder1.AppendLine("</tr>"); stringBuilder1.AppendLine("<tr>"); stringBuilder1.AppendLine("<td class=\"transactionsPropertyTitles\">Datum</td>"); stringBuilder1.AppendLine("<td class=\"transactionsPropertyTitles\">Bedrag</td>"); stringBuilder1.AppendLine("<td class=\"transactionsPropertyTitles\">Betaalmethode</td>"); stringBuilder1.AppendLine("<td class=\"transactionsPropertyTitles\">Afgehandeld door</td>"); stringBuilder1.AppendLine("<td class=\"transactionsPropertyTitles\">Ontvangen</td>"); stringBuilder1.AppendLine("<td class=\"transactionsPropertyTitles\">Wisselgeld</td>"); stringBuilder1.AppendLine("</tr>"); foreach (Transaction transaction in (Collection <Transaction>)ticket.Transactions) { stringBuilder1.AppendLine("<tr>"); stringBuilder1.AppendLine("<td class =\"transactionsPropertyValues\">" + (object)transaction.PayTime + "</td>"); stringBuilder1.AppendLine("<td class =\"transactionsPropertyValues\">" + transaction.Amount.ToString("C") + "</td>"); stringBuilder1.AppendLine("<td class =\"transactionsPropertyValues\">" + (object)transaction.PaymentMethodUsed + "</td>"); stringBuilder1.AppendLine("<td class =\"transactionsPropertyValues\">" + transaction.PaymentHandledBy.Fullname + "</td>"); if (transaction.PaymentMethodUsed == Transaction.PaymentMethod.Cash) { stringBuilder1.AppendLine("<td class =\"transactionsPropertyValues\">" + ((CashTransaction)transaction).MoneyReceived.ToString("C") + "</td>"); stringBuilder1.AppendLine("<td class =\"transactionsPropertyValues\">" + ((CashTransaction)transaction).MoneyReturned.ToString("C") + "</td>"); } else if (transaction.PaymentMethodUsed == Transaction.PaymentMethod.Coin) { stringBuilder1.AppendLine("<td class =\"transactionsPropertyValues\">" + (object)((CoinTransaction)transaction).CoinsReceived + "</td>"); stringBuilder1.AppendLine("<td class =\"transactionsPropertyValues\"></td>"); } else if (transaction.PaymentMethodUsed == Transaction.PaymentMethod.Free) { stringBuilder1.AppendLine("<td class =\"transactionsPropertyValues\" colspan=\"2\">" + ((FreeTransaction)transaction).Reason + "</td>"); } else if (transaction.PaymentMethodUsed == Transaction.PaymentMethod.NFC) { stringBuilder1.AppendLine("<td class =\"transactionsPropertyValues\"></td>"); stringBuilder1.AppendLine("<td class =\"transactionsPropertyValues\"></td>"); } stringBuilder1.AppendLine("</tr>"); } stringBuilder1.AppendLine("</table>"); stringBuilder1.AppendLine("<br />"); } string str4 = new Regex("\\[(\\w+)\\]", RegexOptions.Compiled).Replace(input, (MatchEvaluator)(match => new Dictionary <string, string>((IEqualityComparer <string>)StringComparer.OrdinalIgnoreCase) { { "Title", str1 }, { "ImagePath", Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + "\\Templates\\Html" }, { "TicketOverviewTable", stringBuilder1.ToString() } }[match.Groups[1].Value])); GlobalConfig config = new GlobalConfig(); config.SetMargins(new Margins(70, 45, 70, 45)).SetPaperSize(PaperKind.A4); SimplePechkin simplePechkin = new SimplePechkin(config); ObjectConfig objectConfig = new ObjectConfig(); objectConfig.SetLoadImages(true); objectConfig.SetPrintBackground(true); objectConfig.SetZoomFactor(1.1); objectConfig.SetAllowLocalContent(true); ObjectConfig doc = objectConfig; string html = str4; File.WriteAllBytes(this.FilePath, simplePechkin.Convert(doc, html)); PdfReportService.logger.Info("Ticketoverview PDF created: " + this.FilePath); } catch (Exception ex) { PdfReportService.logger.Error("Could not create temporary PDF file:" + ex.Message); } }
public static void LoadFile(string path, bool append = true) { if (!append) { sConfigs.Clear(); } if (File.Exists(path)) { ObjectConfig currentConfig = null; string currentParamRefId = string.Empty; Type currentParamType = null; IList currentParamList = null; RefListObjectSetting currentParamRefList = null; string currentPropertyName = string.Empty; Regex reInt = new Regex("^[0-9]*$", RegexOptions.None); Regex reDouble = new Regex("^[0-9\\.]*$", RegexOptions.None); XmlUtils.Iterate(path, (XmlNodeInfo nodeInfo) => { if (nodeInfo.Path == "/objects/object") { if (!nodeInfo.IsEndNode) { string attrId = nodeInfo.GetAttribute("id"); if (attrId == null) { throw new Exception("id属性是必须的" + ": " + path + " line " + nodeInfo.Line); } else if (string.IsNullOrWhiteSpace(attrId)) { throw new Exception("id属性不能为空" + ": " + path + " line " + nodeInfo.Line); } string attrClass = nodeInfo.GetAttribute("class"); if (attrClass == null) { throw new Exception("class属性是必须的" + ": " + path + " line " + nodeInfo.Line); } else if (string.IsNullOrWhiteSpace(attrClass)) { throw new Exception("class属性不能为空" + ": " + path + " line " + nodeInfo.Line); } currentConfig = new ObjectConfig(); currentConfig.Id = attrId; currentConfig.Class = attrClass; sConfigs.AddOrUpdate(attrId.ToLower(), currentConfig, (oldKey, oldValue) => { return(currentConfig); }); } else { currentConfig = null; } } else if (nodeInfo.Path == "/objects/object/constructor-arg" || nodeInfo.Path == "/objects/object/property") { if (!nodeInfo.IsEndNode) { if (nodeInfo.Path == "/objects/object/property") { currentPropertyName = nodeInfo.GetAttribute("name"); if (string.IsNullOrWhiteSpace(currentPropertyName)) { throw new Exception("name属性不能为空" + ": " + path + " line " + nodeInfo.Line); } } currentParamRefId = nodeInfo.GetAttribute("ref"); if (string.IsNullOrWhiteSpace(currentParamRefId)) { string typeName = nodeInfo.GetAttribute("type"); if (typeName != null) { if (!string.IsNullOrWhiteSpace(typeName)) { if (!typeName.Contains(".")) { //System下的简单数据类型 currentParamType = Type.GetType("System." + typeName, true, true); } else { //用户自定义类型 currentParamType = AssemblyUtils.GetType(typeName); } } else { throw new Exception("type属性不能为空" + ": " + path + " line " + nodeInfo.Line); } } else { currentParamType = null; } } } else { currentParamRefId = string.Empty; currentParamType = null; currentPropertyName = string.Empty; } } else if (nodeInfo.Path == "/objects/object/constructor-arg/@text") { if (string.IsNullOrWhiteSpace(currentParamRefId)) { string paramValue = nodeInfo.Text.Trim(); handleListValue(currentConfig.ConstructorParams, paramValue, currentParamType, path, nodeInfo.Line); } else { int index = currentConfig.ConstructorParams.Count + currentConfig.RefConstructorParams.Count; currentConfig.RefConstructorParams.Add(new RefObjectSetting(currentParamRefId, index)); } //TODO 对象构造支持更多的参数类型 Hashtable、Dictionary、HashSet等 } else if (nodeInfo.Path == "/objects/object/property/@text") { if (string.IsNullOrWhiteSpace(currentParamRefId)) { string propertyValue = nodeInfo.Text.Trim(); PropertySetting propSetting = new PropertySetting(currentPropertyName, propertyValue); currentConfig.Properties.Add(propSetting); } else { PropertySetting propSetting = new PropertySetting(currentPropertyName); propSetting.RefId = currentParamRefId; currentConfig.Properties.Add(propSetting); } } else if (nodeInfo.Path == "/objects/object/constructor-arg/list" || nodeInfo.Path == "/objects/object/constructor-arg/array") { if (!nodeInfo.IsEndNode) { bool isUserType = false; string typeName = nodeInfo.GetAttribute("type"); if (typeName != null) { if (!string.IsNullOrWhiteSpace(typeName)) { if (!typeName.Contains(".")) { //System下的简单数据类型 currentParamType = Type.GetType("System." + typeName, true, true); } else { //用户自定义类型 currentParamType = AssemblyUtils.GetType(typeName); isUserType = !currentParamType.IsEnum; } } else { throw new Exception("type属性不能为空" + ": " + path + " line " + nodeInfo.Line); } Type geneType = typeof(List <>); Type implType = geneType.MakeGenericType(currentParamType); ConstructorInfo ci = implType.GetConstructor(new Type[] { }); currentParamList = ci.Invoke(new Object[] { }) as IList; } else { currentParamType = Type.GetType("System.Object", true, true); currentParamList = new List <object>(); } if (isUserType) { int index = currentConfig.ConstructorParams.Count + currentConfig.RefConstructorParams.Count; bool isArray = nodeInfo.Path == "/objects/object/constructor-arg/array"; currentParamRefList = new RefListObjectSetting(index, currentParamList, isArray); } } else { if (currentParamRefList == null) { if (nodeInfo.Path == "/objects/object/constructor-arg/list") { currentConfig.ConstructorParams.Add(currentParamList); } else if (nodeInfo.Path == "/objects/object/constructor-arg/array") { Array argArray = Array.CreateInstance(currentParamType, currentParamList.Count); currentParamList.CopyTo(argArray, 0); currentConfig.ConstructorParams.Add(argArray); } } else { currentConfig.RefConstructorParams.Add(currentParamRefList); } currentParamType = null; currentParamList = null; currentParamRefList = null; } } else if (nodeInfo.Path == "/objects/object/constructor-arg/list/value" || nodeInfo.Path == "/objects/object/constructor-arg/array/value") { if (!nodeInfo.IsEndNode) { if (currentParamRefList != null) { currentParamRefId = nodeInfo.GetAttribute("ref"); if (!string.IsNullOrWhiteSpace(currentParamRefId)) { currentParamRefList.ItemList.Add(currentParamRefId); } else { throw new Exception("ref属性不能为空" + ": " + path + " line " + nodeInfo.Line); } } } else { currentParamRefId = string.Empty; } } else if (nodeInfo.Path == "/objects/object/constructor-arg/list/value/@text" || nodeInfo.Path == "/objects/object/constructor-arg/array/value/@text") { if (currentParamRefList == null) { string paramValue = nodeInfo.Text.Trim(); handleListValue(currentParamList, paramValue, currentParamType, path, nodeInfo.Line); } } return(true); }); } }
public void GenerateCheckoutSheet(CheckoutSheet sheet) { try { string input = File.ReadAllText(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + "\\Templates\\Html\\Template_Checkoutsheet.htm"); DateTime dateTime = sheet.OpenTime ?? DateTime.Now; string str1 = "Kasblad JH Tjok Hove: " + dateTime.ToShortDateString(); this.FilePath = Path.GetTempPath() + ("Kasblad JH Tjok Hove " + dateTime.ToString("dd_MM_yyyy HH_mm")) + ".pdf"; List <IGrouping <Product, TicketLine> > list = sheet.Tickets.SelectMany <Ticket, TicketLine>((Func <Ticket, IEnumerable <TicketLine> >)(t => (IEnumerable <TicketLine>)t.TicketLines)).GroupBy <TicketLine, Product>((Func <TicketLine, Product>)(tl => tl.Product)).ToList <IGrouping <Product, TicketLine> >().OrderBy <IGrouping <Product, TicketLine>, string>((Func <IGrouping <Product, TicketLine>, string>)(pl => pl.Key.Name)).ToList <IGrouping <Product, TicketLine> >(); StringBuilder stringBuilder = new StringBuilder(); int num1 = 1; foreach (IGrouping <Product, TicketLine> source in list) { stringBuilder.AppendLine(num1 % 2 > 0 ? "<tr>" : "<tr class=\"alt\">"); stringBuilder.AppendLine("<td>" + source.Key.Name + "</td>"); stringBuilder.AppendLine("<td>" + (object)source.Sum <TicketLine>((Func <TicketLine, int>)(l => (int)l.Amount)) + "</td>"); stringBuilder.AppendLine("</tr>"); ++num1; } Dictionary <string, string> formFields = new Dictionary <string, string>((IEqualityComparer <string>)StringComparer.OrdinalIgnoreCase); formFields.Add("Title", str1); Dictionary <string, string> dictionary1 = formFields; DateTime?nullable = sheet.OpenTime; string str2 = nullable.ToString(); dictionary1.Add("OpeningTime", str2); Dictionary <string, string> dictionary2 = formFields; nullable = sheet.CloseTime; string str3 = nullable.ToString(); dictionary2.Add("ClosureTime", str3); formFields.Add("ClosedBy", sheet.ClosedBy.Fullname); formFields.Add("OpenedBy", sheet.OpenedBy.Fullname); Dictionary <string, string> dictionary3 = formFields; int num2 = sheet.CloseEur500; string str4 = num2.ToString(); dictionary3.Add("AmountEur500", str4); Dictionary <string, string> dictionary4 = formFields; num2 = sheet.CloseEur200; string str5 = num2.ToString(); dictionary4.Add("AmountEur200", str5); Dictionary <string, string> dictionary5 = formFields; num2 = sheet.CloseEur100; string str6 = num2.ToString(); dictionary5.Add("AmountEur100", str6); Dictionary <string, string> dictionary6 = formFields; num2 = sheet.CloseEur50; string str7 = num2.ToString(); dictionary6.Add("AmountEur50", str7); formFields.Add("AmountEur20", sheet.CloseEur20.ToString()); formFields.Add("AmountEur10", sheet.CloseEur10.ToString()); Dictionary <string, string> dictionary7 = formFields; int num3 = sheet.CloseEur5; string str8 = num3.ToString(); dictionary7.Add("AmountEur5", str8); Dictionary <string, string> dictionary8 = formFields; num3 = sheet.CloseEur2; string str9 = num3.ToString(); dictionary8.Add("AmountEur2", str9); formFields.Add("AmountEur1", sheet.CloseEur1.ToString()); Dictionary <string, string> dictionary9 = formFields; int num4 = sheet.CloseEur50c; string str10 = num4.ToString(); dictionary9.Add("AmountEur50c", str10); Dictionary <string, string> dictionary10 = formFields; num4 = sheet.CloseEur20c; string str11 = num4.ToString(); dictionary10.Add("AmountEur20c", str11); Dictionary <string, string> dictionary11 = formFields; num4 = sheet.CloseEur10c; string str12 = num4.ToString(); dictionary11.Add("AmountEur10c", str12); Dictionary <string, string> dictionary12 = formFields; num4 = sheet.CloseEur5c; string str13 = num4.ToString(); dictionary12.Add("AmountEur5c", str13); Dictionary <string, string> dictionary13 = formFields; num4 = sheet.CloseEur2c; string str14 = num4.ToString(); dictionary13.Add("AmountEur2c", str14); Dictionary <string, string> dictionary14 = formFields; num4 = sheet.CloseEur1c; string str15 = num4.ToString(); dictionary14.Add("AmountEur1c", str15); Dictionary <string, string> dictionary15 = formFields; num4 = sheet.CloseEur500 * 500; string str16 = num4.ToString("C"); dictionary15.Add("SubtotalEur500", str16); Dictionary <string, string> dictionary16 = formFields; num4 = sheet.CloseEur200 * 200; string str17 = num4.ToString("C"); dictionary16.Add("SubtotalEur200", str17); Dictionary <string, string> dictionary17 = formFields; num4 = sheet.CloseEur100 * 100; string str18 = num4.ToString("C"); dictionary17.Add("SubtotalEur100", str18); Dictionary <string, string> dictionary18 = formFields; num4 = sheet.CloseEur50 * 50; string str19 = num4.ToString("C"); dictionary18.Add("SubtotalEur50", str19); Dictionary <string, string> dictionary19 = formFields; num4 = sheet.CloseEur20 * 20; string str20 = num4.ToString("C"); dictionary19.Add("SubtotalEur20", str20); Dictionary <string, string> dictionary20 = formFields; num4 = sheet.CloseEur10 * 10; string str21 = num4.ToString("C"); dictionary20.Add("SubtotalEur10", str21); Dictionary <string, string> dictionary21 = formFields; num4 = sheet.CloseEur5 * 5; string str22 = num4.ToString("C"); dictionary21.Add("SubtotalEur5", str22); Dictionary <string, string> dictionary22 = formFields; num4 = sheet.CloseEur2 * 2; string str23 = num4.ToString("C"); dictionary22.Add("SubtotalEur2", str23); Dictionary <string, string> dictionary23 = formFields; num4 = sheet.CloseEur1 * 1; string str24 = num4.ToString("C"); dictionary23.Add("SubtotalEur1", str24); Dictionary <string, string> dictionary24 = formFields; double num5 = (double)sheet.CloseEur50c * 0.5; string str25 = num5.ToString("C"); dictionary24.Add("SubtotalEur50c", str25); Dictionary <string, string> dictionary25 = formFields; num5 = (double)sheet.CloseEur20c * 0.2; string str26 = num5.ToString("C"); dictionary25.Add("SubtotalEur20c", str26); Dictionary <string, string> dictionary26 = formFields; num5 = (double)sheet.CloseEur10c * 0.1; string str27 = num5.ToString("C"); dictionary26.Add("SubtotalEur10c", str27); Dictionary <string, string> dictionary27 = formFields; num5 = (double)sheet.CloseEur5c * 0.05; string str28 = num5.ToString("C"); dictionary27.Add("SubtotalEur5c", str28); Dictionary <string, string> dictionary28 = formFields; num5 = (double)sheet.CloseEur2c * 0.02; string str29 = num5.ToString("C"); dictionary28.Add("SubtotalEur2c", str29); Dictionary <string, string> dictionary29 = formFields; num5 = (double)sheet.CloseEur1c * 0.01; string str30 = num5.ToString("C"); dictionary29.Add("SubtotalEur1c", str30); Dictionary <string, string> dictionary30 = formFields; num5 = sheet.CloseAmount; string str31 = num5.ToString("C"); dictionary30.Add("EndTotal", str31); Dictionary <string, string> dictionary31 = formFields; num5 = sheet.OpenAmount; string str32 = num5.ToString("C"); dictionary31.Add("BeginTotal", str32); Dictionary <string, string> dictionary32 = formFields; num5 = sheet.CloseAmount - sheet.OpenAmount; string str33 = num5.ToString("C"); dictionary32.Add("Revenue", str33); formFields.Add("Remarks", sheet.Comments); formFields.Add("ImagePath", Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + "\\Templates\\Html"); formFields.Add("TableSoldProducts", stringBuilder.ToString()); string str34 = new Regex("\\[(\\w+)\\]", RegexOptions.Compiled).Replace(input, (MatchEvaluator)(match => formFields[match.Groups[1].Value])); GlobalConfig config = new GlobalConfig(); config.SetMargins(new Margins(70, 45, 70, 45)).SetPaperSize(PaperKind.A4); SimplePechkin simplePechkin = new SimplePechkin(config); ObjectConfig objectConfig = new ObjectConfig(); objectConfig.SetLoadImages(true); objectConfig.SetPrintBackground(true); objectConfig.SetZoomFactor(1.1); objectConfig.SetAllowLocalContent(true); ObjectConfig doc = objectConfig; string html = str34; File.WriteAllBytes(this.FilePath, simplePechkin.Convert(doc, html)); PdfReportService.logger.Info("Checkoutsheet PDF created: " + this.FilePath); } catch (Exception ex) { PdfReportService.logger.Error("Could not create temporary PDF file:" + ex.Message); } }
public void Register(Transform transform) { configurations[transform] = new ObjectConfig(); }
public void GenerateMemberCardList(List <Member> members) { string input = File.ReadAllText(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + "\\Templates\\Html\\Template_Membercardlist.htm"); string str1 = "Lidkaarten: " + DateTime.Now.ToShortDateString(); this.FilePath = Path.GetTempPath() + ("tmp" + Util.Util.RandomString(10)) + ".pdf"; StringBuilder stringBuilder = new StringBuilder(); foreach (Member member in members) { stringBuilder.AppendLine("<table class=\"table3\">"); stringBuilder.AppendLine("<tr>"); stringBuilder.AppendLine("<td colspan=\"6\" class=\"memberTitle\">" + member.LastName + " " + member.FirstName + "</td>"); stringBuilder.AppendLine("</tr>"); stringBuilder.AppendLine("<tr>"); stringBuilder.AppendLine("<td class=\"memberPropertyTitles\">Postcode</td>"); stringBuilder.AppendLine("<td class=\"memberPropertyTitles\">Gemeente</td>"); stringBuilder.AppendLine("<td class=\"memberPropertyTitles\" colspan=\"2\">Adres</td>"); stringBuilder.AppendLine("<td class=\"memberPropertyTitles\">Land</td>"); stringBuilder.AppendLine("<td class=\"memberPropertyTitles\">Geslacht</td>"); stringBuilder.AppendLine("</tr>"); stringBuilder.AppendLine("<tr>"); stringBuilder.AppendLine("<td class=\"memberPropertyValues\">" + member.ZipCode + "</td>"); stringBuilder.AppendLine("<td class=\"memberPropertyValues\">" + member.City + "</td>"); stringBuilder.AppendLine("<td class=\"memberPropertyValues\" colspan=\"2\">" + member.Address + "</td>"); stringBuilder.AppendLine("<td class=\"memberPropertyValues\">" + member.Country + "</td>"); stringBuilder.AppendLine("<td class=\"memberPropertyValues\">" + (member.Gender == Member.Genders.Female ? "Vrouw" : "Man") + "</td>"); stringBuilder.AppendLine("</tr>"); stringBuilder.AppendLine("<tr>"); stringBuilder.AppendLine("<td class=\"memberPropertyTitles\" colspan=\"2\">Geboortedatum</td>"); stringBuilder.AppendLine("<td class=\"memberPropertyTitles\" colspan=\"2\">E-mail adres</td>"); stringBuilder.AppendLine("<td class=\"memberPropertyTitles\" colspan=\"2\">Telefoonnummer</td>"); stringBuilder.AppendLine("</tr>"); DateTime dateTime = member.BirthDate ?? new DateTime(); stringBuilder.AppendLine("<tr>"); stringBuilder.AppendLine("<td class=\"memberPropertyValues\" colspan=\"2\">" + dateTime.ToShortDateString() + "</td>"); stringBuilder.AppendLine("<td class=\"memberPropertyValues\" colspan=\"2\">" + member.Email + "</td>"); stringBuilder.AppendLine("<td class=\"memberPropertyValues\" colspan=\"2\">" + member.TelephoneNr + "</td>"); stringBuilder.AppendLine("</tr>"); stringBuilder.AppendLine("<tr>"); stringBuilder.AppendLine("<td colspan=\"6\"> </td>"); stringBuilder.AppendLine("</tr>"); stringBuilder.AppendLine("<tr>"); stringBuilder.AppendLine(" <td colspan=\"6\" class=\"memberCardTitle\">Lidkaarten</td>"); stringBuilder.AppendLine("</tr>"); stringBuilder.AppendLine("<tr>"); stringBuilder.AppendLine("<td class=\"memberCardPropertyTitles\">Aanmaakdatum</td>"); stringBuilder.AppendLine("<td class=\"memberCardPropertyTitles\">Vervaldatum</td>"); stringBuilder.AppendLine("<td class=\"memberCardPropertyTitles\">Actief lid</td>"); stringBuilder.AppendLine("<td class=\"memberCardPropertyTitles\">Afgedrukt</td>"); stringBuilder.AppendLine("<td class=\"memberCardPropertyTitles\">Kaart ID</td>"); stringBuilder.AppendLine("<td class=\"memberCardPropertyTitles\">Aangemaakt door</td>"); stringBuilder.AppendLine("</tr>"); foreach (MemberCard memberCard in (Collection <MemberCard>)member.MemberCards) { stringBuilder.AppendLine("<tr>"); stringBuilder.AppendLine("<td class =\"memberCardPropertyValues\">" + memberCard.CreationTime.ToShortDateString() + "</td>"); stringBuilder.AppendLine("<td class =\"memberCardPropertyValues\">" + memberCard.ExpireDate.ToShortDateString() + "</td>"); stringBuilder.AppendLine("<td class =\"memberCardPropertyValues\">" + (memberCard.ActiveMember ? "Ja" : "Nee") + "</td>"); stringBuilder.AppendLine("<td class =\"memberCardPropertyValues\">" + (memberCard.Printed ? "Ja" : "Nee") + "</td>"); stringBuilder.AppendLine("<td class =\"memberCardPropertyValues\">" + memberCard.SmartCardId + "</td>"); stringBuilder.AppendLine("<td class =\"memberCardPropertyValues\">" + (memberCard.CreatedBy != null ? memberCard.CreatedBy.Fullname : string.Empty) + "</td>"); stringBuilder.AppendLine("</tr>"); } stringBuilder.AppendLine("</table>"); stringBuilder.AppendLine("<br />"); } string str2 = new Regex("\\[(\\w+)\\]", RegexOptions.Compiled).Replace(input, (MatchEvaluator)(match => new Dictionary <string, string>((IEqualityComparer <string>)StringComparer.OrdinalIgnoreCase) { { "Title", str1 }, { "ImagePath", Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + "\\Templates\\Html" }, { "MemberCardOverviewTable", stringBuilder.ToString() } }[match.Groups[1].Value])); GlobalConfig config = new GlobalConfig(); config.SetMargins(new Margins(70, 45, 70, 45)).SetPaperSize(PaperKind.A4); SimplePechkin simplePechkin = new SimplePechkin(config); ObjectConfig objectConfig = new ObjectConfig(); objectConfig.SetLoadImages(true); objectConfig.SetPrintBackground(true); objectConfig.SetZoomFactor(1.1); objectConfig.SetAllowLocalContent(true); ObjectConfig doc = objectConfig; string html = str2; File.WriteAllBytes(this.FilePath, simplePechkin.Convert(doc, html)); PdfReportService.logger.Info("Membercardlist PDF created: " + this.FilePath); }
/// <summary> /// Runs conversion process. /// /// Allows to convert both external HTML resource and HTML string. /// </summary> /// <param name="doc">document parameters</param> /// <param name="html">document body, ignored if <code>ObjectConfig.SetPageUri</code> is set</param> /// <returns>PDF document body</returns> public byte[] Convert(ObjectConfig doc, string html) { return (byte[])_synchronizer.Invoke((Func<IPechkin, ObjectConfig, string, byte[]>)((conv, obj, txt) => conv.Convert(obj, txt)), new object[]{ _converter, doc, html }); }
public void Elabora(string XmlDaImpotare) { string xslFile = @"C:\TestEdicom\fatturaordinaria_v1.2.1.xsl"; string xmlFile = XmlDaImpotare; string htmlFile = @"C:\TestEdicom\prova.HTML"; string _NomePdf = NomePDF(XmlDaImpotare); listBox1.Items.Add(_NomePdf); XslCompiledTransform transform = new XslCompiledTransform(); transform.Load(xslFile); transform.Transform(xmlFile, htmlFile); //MessageBox.Show("Ho ottenuto HTML"); //EO.Pdf.HtmlToPdf.ConvertHtml( @"C:\TestEdicom\prova.HTML", @"C:\TestEdicom\prova.pdf"); // create global configuration object GlobalConfig gc = new GlobalConfig(); // set it up using fluent notation // Remember to import the following type: // using System.Drawing.Printing; // // a new instance of Margins with 1-inch margins. gc.SetMargins(new Margins(100, 100, 100, 100)) .SetDocumentTitle("Test document") .SetPaperSize(PaperKind.Letter); // Create converter IPechkin pechkin = new SynchronizedPechkin(gc); // Create document configuration object ObjectConfig configuration = new ObjectConfig(); string HTML_FILEPATH = @"C:\TestEdicom\prova.HTML"; // and set it up using fluent notation too configuration .SetAllowLocalContent(true) .SetPageUri(@"file:///" + HTML_FILEPATH); // Generate the PDF with the given configuration // The Convert method will return a Byte Array with the content of the PDF // You will need to use another method to save the PDF (mentioned on step #3) byte[] pdfContent = pechkin.Convert(configuration); // Folder where the file will be created string directory = @"C:\TestEdicom\" + _NomePdf; if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } // Name of the PDF string filename = _NomePdf + ".pdf"; if (ByteArrayToFile(directory + "\\" + filename, pdfContent)) { Console.WriteLine("PDF Succesfully created"); } else { Console.WriteLine("Cannot create PDF"); } //MessageBox.Show("Ho generato PDF"); File.Move(XmlDaImpotare, Path.GetDirectoryName(XmlDaImpotare) + "\\Park\\" + Path.GetFileName(XmlDaImpotare)); File.Copy(Path.GetDirectoryName(XmlDaImpotare) + "\\DATI PER REGISTRAZIONE.xlsx", directory + "\\DATI PER REGISTRAZIONE.xlsx"); }
/// <summary> /// Converts external HTML resource into PDF. /// </summary> /// <param name="doc">document parameters, <code>ObjectConfig.SetPageUri</code> should be set</param> /// <returns>PDF document body</returns> public byte[] Convert(ObjectConfig doc) { return((byte[])_synchronizer.Invoke((Func <IwkHtmlToPdfSharp, ObjectConfig, byte[]>)((conv, obj) => conv.Convert(obj)), new object[] { _converter, doc })); }
/// <summary> /// Converts external HTML resource into PDF. /// </summary> /// <param name="doc">document parameters, <code>ObjectConfig.SetPageUri</code> should be set</param> /// <returns>PDF document body</returns> public byte[] Convert(ObjectConfig doc) { return (byte[])_synchronizer.Invoke((Func<IPechkin, ObjectConfig, byte[]>)((conv, obj) => conv.Convert(obj)), new object[] { _converter, doc }); }
static void Main(string[] args) { Thread.CurrentThread.SetApartmentState(ApartmentState.STA); maxTreadNumber = int.Parse(ConfigurationManager.AppSettings["MaxThreadNumber"].ToString()); string[] paras = args[0].Split(','); environment = paras[0]; switch (environment) { case "1": environment = "DEV"; break; case "2": environment = "QA"; break; case "3": environment = "UAT"; break; case "4": environment = "PROD"; break; default: break; } // get data from databases string connetionStr = ConfigurationManager.ConnectionStrings["SQL" + environment].ConnectionString; string cmd = "SELECT [ID],[Control_ID],[Claim_Number],[Claimant_Number],[Form_ID],[sequence],[FormName] ,[URL],[URLDate],[URLFlag],[AttachmentName],[PDFName],[PDFDate] ,[Processed] FROM test where id> (1591748 +" + (1000 * int.Parse(paras[1])).ToString() + ") and id<=(1591748 +" + (1000 * int.Parse(paras[1]) + 1000).ToString() + ")";// [TRANSFORMDB].[dbo].[CMT_ASPX_to_PDF_URL]"; using (SqlConnection sc = new SqlConnection(connetionStr)) { SqlCommand scmd = new SqlCommand(cmd, sc); try { sc.Open(); SqlDataAdapter sda = new SqlDataAdapter(scmd); DataSet sd = new DataSet(); sda.Fill(sd); dataRowQueue = new ConcurrentQueue <DataRow>(sd.Tables[0].AsEnumerable().ToList <DataRow>()); sda.Dispose(); } catch (Exception e) { throw e; } } //get the html contents while (threadNumber < maxTreadNumber) { //control thread amount threadNumber++; var thread = getWebBrowerThread(); //thread.SetApartmentState(ApartmentState.STA); thread.Start(); } Console.WriteLine("started"); while (dataRowQueue != null && dataRowQueue.Count > 0 && htmlQueue.Count == 0) { Thread.Sleep(1000); } while (pdfThreadNumber < maxTreadNumber) { pdfThreadNumber++; Thread pdfThread = new Thread(() => { GlobalConfig gc = new GlobalConfig(); gc.SetMargins(new Margins(100, 100, 100, 100)); gc.SetPaperSize(PaperKind.Letter); IPechkin pechkin = new SimplePechkin(gc); ObjectConfig configuration = new ObjectConfig(); configuration.SetCreateExternalLinks(true).SetFallbackEncoding(Encoding.UTF8).SetLoadImages(true).SetCreateForms(false); /*test error*/ int m = 0; /*end*/ while (htmlQueue.Count != 0) { //while(threadNumber>=maxTreadNumber) // { // Thread.Sleep(1000); // } /*test error*/ m++; if (m == 50) { throw (new Exception("forced")); } /*end*/ while (dataRowQueue != null && dataRowQueue.Count > 0 && htmlQueue.Count == 0) { Thread.Sleep(1000); } /*isProcessDone = false; * var subThread = new Thread(() => * {*/ //threadNumber++; DataRow dr; if (htmlQueue.TryDequeue(out dr)) { rounds++; try { byte[] pdfBuf = pechkin.Convert(configuration, dr["URL"].ToString()); var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "testpdf\\" + dr["Claim_Number"].ToString() + "_" + dr["Claimant_Number"].ToString() + "_" + dr["Form_ID"].ToString() + "_" + dr["sequence"].ToString() + ".pdf"); System.IO.File.WriteAllBytes(testFile, pdfBuf); pdfBuf = null; dr.Delete(); dr = null; testFile = null; } catch (Exception e) { MessageBox.Show(e.Message); } if (rounds % 1000 == 0) { GC.Collect(); GC.WaitForPendingFinalizers(); } } Application.ApplicationExit += Application_PDFApplicationExit; Application.ExitThread(); Application.Exit(); } }); pdfThread.Start(); } }