/// <summary> /// Returns pdf content based on html content /// </summary> /// <param name="headerHtml"></param> /// <param name="bodyHtml"></param> /// <param name="footerHtml"></param> /// <param name="templateOption"></param> /// <returns></returns> public Byte[] CreatePDFBasedOnHTMLTemplate(string headerHtml, string bodyHtml, string footerHtml, TemplateOption templateOption = null) { string baseUrl = string.Empty; HtmlToPdf htmlToPdfConverter = new HtmlToPdf(); PdfDocumentControl doc = htmlToPdfConverter.Document; doc.FontEmbedding = true; this.templateOption = templateOption; if (templateOption != null) { if (templateOption.PageMargin != null) { htmlToPdfConverter.PageLayoutingEvent += htmlToPdfConverter_PageLayoutingEvent; htmlToPdfConverter.Document.Margins = new PdfMargins(templateOption.PageMargin.LeftMargin, templateOption.PageMargin.RightMargin, templateOption.PageMargin.TopMargin, templateOption.PageMargin.BottomMargin); } // Setting page orientation if (templateOption.IsLandscapeOrientation) { htmlToPdfConverter.Document.PageOrientation = PdfPageOrientation.Landscape; } } htmlToPdfConverter.SerialNumber = "bad=="; // set header and footer SetHeader(htmlToPdfConverter.Document, headerHtml, baseUrl, templateOption); SetFooter(htmlToPdfConverter.Document, footerHtml, baseUrl, templateOption); return(htmlToPdfConverter.ConvertHtmlToMemory(bodyHtml, baseUrl)); }
private void mnuBuild_Click(object sender, EventArgs e) { TemplateDefinition template = null; if (StaticUnity.TemplateProvider == null || (template = StaticUnity.Template) == null) { MessageBoxHelper.ShowExclamation("你还没有选择生成模板,请从【模板】菜单中选择。"); return; } if (lstObject.SelectedItems.Count == 0) { return; } var item = lstObject.SelectedItems[0]; if (item.Tag is Column) { item = item.Parent; } var table = item.Tag as Table; var option = new TemplateOption(); option.Template = template; option.Partitions = StaticUnity.Template.GetAllPartitions(); option.DynamicAssemblies.AddRange(StaticUnity.DynamicAssemblies); option.Profile = StaticUnity.Profile; var tables = new List <Table> { table }; Cursor = Cursors.WaitCursor; try { var result = StaticUnity.TemplateProvider.GenerateFiles(option, tables, null); if (result != null) { foreach (var file in result) { var editor = new frmEditor { GenerateResult = file }; editor.Show(this.DockPanel, WeifenLuo.WinFormsUI.Docking.DockState.Document); } } } finally { Cursor = Cursors.Default; } }
public List <GenerateResult> GenerateFiles(TemplateOption option, List <Table> tables, CodeGenerateHandler handler) { try { return(GenerateInternal(option, tables, handler)); } catch (Exception exp) { MessageBoxHelper.ShowError(exp.Message); return(null); } }
private List <GenerateResult> GenerateInternal(TemplateOption option, List <Table> tables, CodeGenerateHandler handler) { var result = new List <GenerateResult>(); var references = new List <Reference>(); foreach (var table in tables) { references.AddRange(table.ForeignKeys); } var tparts = option.Partitions.Where(s => s.Loop == PartitionLoop.Tables).ToList(); var nparts = option.Partitions.Where(s => s.Loop == PartitionLoop.None).ToList(); var engine = new VelocityEngine(); foreach (var table in tables) { var context = new VelocityContext(); context.Put("Tables", tables); context.Put("References", references); context.Put("Current", table); context.Put("Profile", option.Profile); foreach (var part in option.Partitions) { var props = new ExtendedProperties(); var info = new FileInfo(part.FilePath); props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file"); props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, info.DirectoryName); props.AddProperty(RuntimeConstants.COUNTER_INITIAL_VALUE, "0"); engine.Init(props); using (var writer = new StringWriter()) { engine.MergeTemplate(info.Name, "gb2312", context, writer); var r = new GenerateResult(part, writer.ToString()); if (option.WriteToDisk && r.WriteToDisk) { PartitionWriter.Write(r, table, option.Profile, option.OutputDirectory); } result.Add(r); } } } return(result); }
private ExcelTemplateDefinition Execute(string templateName, ExcelInterop.Range templateDeclarationFirstCell) { ExcelInterop.Worksheet worksheet = null; try { if (string.IsNullOrEmpty(templateName)) { throw new EtkException("Template name cannot be null or empty."); } if (templateDeclarationFirstCell == null) { throw new EtkException("Template caller cannot be null."); } //Get template option XmlExcelTemplateOption xmlTemplateOption = (templateDeclarationFirstCell.Value2 as string).Deserialize <XmlExcelTemplateOption>(); TemplateOption templateOption = new TemplateOption(xmlTemplateOption); // Get the template end. worksheet = templateDeclarationFirstCell.Worksheet; ExcelInterop.Range templateDeclarationLastRange = worksheet.Cells.Find(string.Format(TEMPLATE_END_FORMAT, templateName), Type.Missing, ExcelInterop.XlFindLookIn.xlValues, ExcelInterop.XlLookAt.xlPart, ExcelInterop.XlSearchOrder.xlByRows, ExcelInterop.XlSearchDirection.xlNext, false); if (templateDeclarationLastRange == null) { throw new EtkException($"Cannot find the end of template '{templateName.EmptyIfNull()}' in sheet '{worksheet.Name.EmptyIfNull()}'"); } ExcelTemplateDefinition excelTemplateDefinition = new ExcelTemplateDefinition(templateDeclarationFirstCell, templateDeclarationLastRange, templateOption); ExcelTemplateDefinitionPart header, body, footer; ParseTemplate(excelTemplateDefinition, ref worksheet, out header, out body, out footer); excelTemplateDefinition.ExcelInit(header, body, footer); return(excelTemplateDefinition); } catch (Exception ex) { throw new EtkException($"Cannot create the template '{templateName.EmptyIfNull()}'. {ex.Message}"); } finally { if (worksheet != null) { ExcelApplication.ReleaseComObject(worksheet); worksheet = null; } } }
public List <GenerateResult> GenerateFiles(TemplateOption option, List <Table> tables, CodeGenerateHandler handler) { var scope = new SingleAppDomainScope(); try { return(GenerateInternal(option, tables, handler)); } catch (Exception exp) { MessageBoxHelper.ShowError(exp.Message); return(null); } finally { scope.Dispose(); } }
/// <summary> /// Create Invoice action /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnCreateInvoice_Click(object sender, EventArgs e) { DocumentTemplate template = new DocumentTemplate(); template.HeaderCsHtml = txbHeader.Text; template.BodyCsHtml = txbBody.Text; template.FooterCsHtml = txbFooter.Text; string templateOptionsJson = txbTemplateOption.Text; List <TemplateOption> templateOptionsList = new JavaScriptSerializer().Deserialize <List <TemplateOption> >(templateOptionsJson); TemplateOption templateOptions = templateOptionsList[0]; CreatePDFBasedOnCsHtmlTemplate(template, txbOutput.Text, templateOptions); MessageBox.Show(txbOutput.Text + " was created successfully."); }
internal override Func <HelpContext, string?>?GetCustomFirstColumnText(TemplateOption o) { return((context) => { string standardUsage = HelpBuilder.Default.GetIdentifierSymbolUsageLabel(o.Option, context); if (standardUsage.Length > context.HelpBuilder.MaxWidth / 3) { if (Choices.Count > 2) { o.Option.ArgumentHelpName = $"{string.Join("|", Choices.Keys.Take(2))}|..."; string updatedFirstColumn = HelpBuilder.Default.GetIdentifierSymbolUsageLabel(o.Option, context); if (updatedFirstColumn.Length <= context.HelpBuilder.MaxWidth / 3) { return updatedFirstColumn; } } o.Option.ArgumentHelpName = HelpStrings.Text_ChoiceArgumentHelpName; return HelpBuilder.Default.GetIdentifierSymbolUsageLabel(o.Option, context); } return standardUsage; }); }
internal ExcelTemplateDefinition(ExcelInterop.Range firstRange, ExcelInterop.Range lastRange, TemplateOption templateOption) : base(templateOption) { DefinitionFirstCell = firstRange; DefinitionLastCell = lastRange; Width = DefinitionLastCell.Column - DefinitionFirstCell.Column + 1; Height = DefinitionLastCell.Row - DefinitionFirstCell.Row + 1; }
public static List <TempOptionParamsDetails> PopulateTempOptionParamsDetailsCollection(TemplateOption templateOptions) { List <TempOptionParamsDetails> result = new List <TempOptionParamsDetails>(); foreach (var item in templateOptions.TempOptionParams) { result.Add(new TempOptionParamsDetails { ParameterId = item.ParameterId, ParameterName = item.ParameterName, ParameterTooltip = item.ParameterTooltip, ParameterPrice = item.ParameterPrice, ParentOptionId = item.ParentOptionId, ParameterSale = item.ParameterSale }); } return(result); }
public ViewResult CreateEdit(Guid?Id, string type, string game = null) { switch (type) { case "Product": Product prod = _context.Products.Where(p => p.ProductId == Id). Include(p => p.ProductGame). Include(p => p.ProductDescription). Include(p => p.ProductPrices). Include(p => p.ProductCategory). Include(p => p.ProductSubCategory). Include(p => p.ProductSeo).FirstOrDefault(); ProductDetails productDetails = new ProductDetails(); if (prod != null) { productDetails = _mapper.Map <Product, ProductDetails>(prod); productDetails = _mapper.Map(prod.ProductDescription, productDetails); productDetails = _mapper.Map(prod.ProductPrices.FirstOrDefault(), productDetails); //productDetails = _mapper.Map<ProductDetails>(prod); //productDetails = _mapper.Map<ProductDetails>(prod.ProductDescription);1 //productDetails = _mapper.Map<ProductDetails>(prod.ProductPrices.FirstOrDefault()); productDetails.GamesList = new SelectList(_context.ProductGames.Select(g => g.GameName), prod.ProductGame?.GameName ?? "Select Game"); productDetails.CategoriesList = new SelectList(_context.ProductCategories.Where(c => c.ProductGame.GameName == prod.ProductGame.GameName).Select(c => c.ProductCategoryName), prod.ProductCategory?.ProductCategoryName ?? "Select Category"); productDetails.MetaTagTitleList = new SelectList(_context.Seos.Select(s => s.MetaTagTitle), prod.ProductSeo?.MetaTagTitle ?? "Select Meta tag title"); //TODO:ProductSubCategory productDetails.SubCategoriesList = new SelectList(_context.ProductSubCategories.Select(sc => sc.ProductCategoryName), prod.ProductSubCategory?.ProductCategoryName ?? "Select Product Sub Category Name"); return(View("Save" + type, productDetails)); } else { //TODO: Вытащи все название игр,категорий и метатэгов productDetails.GamesList = new SelectList(_context.ProductGames.Select(g => g.GameName), prod.ProductGame.GameName ?? "Select Game"); productDetails.CategoriesList = new SelectList(_context.ProductCategories.Where(c => c.ProductGame.GameName == prod.ProductGame.GameName).Select(c => c.ProductCategoryName), prod.ProductCategory.ProductCategoryName ?? "Select Category"); productDetails.MetaTagTitleList = new SelectList(_context.Seos.Select(s => s.MetaTagTitle), prod.ProductSeo.MetaTagTitle ?? "Select Meta tag title"); return(View("Save" + type, productDetails)); } case "TemplateOption": TemplateOption templateOption = _context.TemplateOptions.Where(p => p.OptionId == Id).Include(p => p.TempOptionParams).FirstOrDefault(); TemplateOptionDetails templateOptionDetails = new TemplateOptionDetails(); if (templateOption != null) { templateOptionDetails = _mapper.Map <TemplateOption, TemplateOptionDetails>(templateOption); return(View("Save" + type, templateOption)); } else { return(View("Save" + type, templateOption)); } case "ProductGame": ProductGame productGame = _context.ProductGames.Where(p => p.ProductGameId == Id).FirstOrDefault(); if (productGame != null) { return(View("Save" + type, productGame)); } else { return(View("Save" + type, productGame)); { ViewBag.MetaTagTitleList = new SelectList(_context.Seos.Select(s => s.MetaTagTitle), "Select Meta tag title from List"); }; } case "HtmlBlocks": HtmlBlock siteBlock = _context.HtmlBlocks.Where(p => p.SiteBlockId == Id).Include(p => p.HtmlBlocksChildren).FirstOrDefault(); if (siteBlock != null) { return(View("Save" + type, siteBlock)); } else { //TODO: Children //var result = new HtmlBlock { SiteBlockId = Guid.NewGuid(), HtmlBlocksChildren = new List<HtmlBlock.HtmlBlocksChildren>() }; return(View("Save" + type, siteBlock)); } case "SEO": Seo seo = _context.Seos.Where(p => p.Seoid == Id).FirstOrDefault(); if (seo != null) { return(View("Save" + type, seo)); } else { return(View("Save" + type, seo)); } case "Users": User user = _context.Users.Where(p => p.UserId == Id).FirstOrDefault(); if (user != null) { return(View("Save" + type, user)); } else { return(View("Save" + type, user)); } case "Ranks": Rank ranks = _context.Ranks.Where(p => p.RankId == Id).FirstOrDefault(); if (ranks != null) { return(View("Save" + type, ranks)); } else { return(View("Save" + type, ranks)); } case "Customers": Customer customers = _context.Customers.Where(p => p.CustomerId == Id).FirstOrDefault(); if (customers != null) { return(View("Save" + type, customers)); } else { return(View("Save" + type, customers)); } case "Roles": Role roles = _context.Roles.Where(p => p.RoleId == Id).FirstOrDefault(); if (roles != null) { return(View("Save" + type, roles)); } else { return(View("Save" + type, roles)); } case "Article": Article article = _context.Articles.Where(p => p.ArticleId == Id).FirstOrDefault(); if (article != null) { ViewBag.MetaTagTitleList = new SelectList(_context.Seos.Select(s => s.MetaTagTitle), "Select Meta tag title from List"); ViewBag.GamesList = new SelectList(_context.ProductGames.Select(g => g.GameName), "Select Game"); return(View("Save" + type, article)); } else { return(View("Save" + type, article)); { ViewBag.MetaTagTitleList = new SelectList(_context.Seos.Select(s => s.MetaTagTitle), "Select Meta tag title from List"); ViewBag.GamesList = new SelectList(_context.ProductGames.Select(g => g.GameName), "Select Game"); }; } case "Orders": Order orders = _context.Orders.Where(p => p.OrderId == Id).FirstOrDefault(); if (orders != null) { return(View("Save" + type, orders)); } else { return(View("Save" + type, orders)); } case "ProductCategory": ProductCategory productCategory = _context.ProductCategories.Where(p => p.ProductCategoryId == Id).FirstOrDefault(); if (productCategory != null) { ViewBag.MetaTagTitleList = new SelectList(_context.Seos.Select(s => s.MetaTagTitle), "Select Meta tag title from List"); ViewBag.GamesList = new SelectList(_context.ProductGames.Select(g => g.GameName), "Select Game"); return(View("Save" + type, productCategory)); } else { return(View("Save" + type, productCategory)); { ViewBag.MetaTagTitleList = new SelectList(_context.Seos.Select(s => s.MetaTagTitle), "Select Meta tag title from List"); ViewBag.GamesList = new SelectList(_context.ProductGames.Select(g => g.GameName), "Select Game"); }; } case "ProductSubCategory": ProductSubCategory productSubCategory = _context.ProductSubCategories.Where(p => p.ProductSubCategoryId == Id).FirstOrDefault(); if (productSubCategory != null) { return(View("Save" + type, productSubCategory)); } else { return(View("Save" + type, productSubCategory)); { ViewBag.MetaTagTitleList = new SelectList(_context.Seos.Select(s => s.MetaTagTitle), "Select Meta tag title from List"); ViewBag.CategoryList = new SelectList(_context.ProductCategories.Select(s => s.ProductCategoryName), "Select Product Category from List"); }; } default: return(View("Admin")); } }
private GenerateResult ProcessPartitionCodeFile(PartitionDefinition part, object schema, object profile, TemplateOption option, string content) { var result = new GenerateResult(part, content); if (option.WriteToDisk && result.WriteToDisk) { PartitionWriter.Write(result, schema, profile, option.OutputDirectory); } return(result); }
private List <GenerateResult> GenerateInternal(TemplateOption option, List <Table> tables, CodeGenerateHandler handler) { var result = new List <GenerateResult>(); var references = new List <Reference>(); foreach (var table in tables) { references.AddRange(table.ForeignKeys); } var tparts = option.Partitions.Where(s => s.Loop == PartitionLoop.Tables).ToList(); var nparts = option.Partitions.Where(s => s.Loop == PartitionLoop.None).ToList(); var count = tparts.Count * tables.Count + nparts.Count; var index = 0; var calc = new Func <int, int>(i => { return((int)((i / (count * 1.0)) * 100)); }); InitializeNamespaces(); foreach (var table in tables) { var model = new { Tables = tables, References = references, Current = table, Profile = option.Profile }; if (Processor.IsCancellationRequested()) { break; } foreach (var part in tparts) { if (Processor.IsCancellationRequested()) { break; } if (handler != null) { handler(table.Name, calc(++index)); } var info = new FileInfo(part.FilePath); var content = ReplaceIncludeTemplate(info.DirectoryName, part.Content); var code = RazorEngine.Razor.Parse(content, model); var r = ProcessPartitionCodeFile(part, table, option.Profile, option, code); if (r != null) { result.Add(r); } } } foreach (var part in nparts) { if (Processor.IsCancellationRequested()) { break; } if (handler != null) { handler("全局", calc(++index)); } var model = new { Tables = tables, References = references, Profile = option.Profile }; var info = new FileInfo(part.FilePath); var content = ReplaceIncludeTemplate(info.DirectoryName, part.Content); var code = RazorEngine.Razor.Parse(content, model); var r = ProcessPartitionCodeFile(part, null, option.Profile, option, code); if (r != null) { result.Add(r); } } if (option.WriteToDisk) { ResourceWriter.Write(option.Template, option.OutputDirectory); } return(result); }
/// <summary> /// This function is used for creating the invoice based on cshtml templates /// </summary> /// <param name="documentTemplate"></param> /// <param name="filePathToSave"></param> /// <param name="templateOption"></param> /// <returns></returns> public bool CreatePDFBasedOnCsHtmlTemplate(DocumentTemplate documentTemplate, string filePathToSave, TemplateOption templateOption = null) { FileStream objFileStream = null; try { string headerHtml = string.Empty; string bodyHtml = string.Empty; string footerHtml = string.Empty; documentTemplate.InvoicePdfGenerationDetails = new InvoicePdfGenerationDetails() { ImagesFolderRootPath = "" }; if (!string.IsNullOrWhiteSpace(documentTemplate.HeaderCsHtml)) { // Getting the header html headerHtml = RazorBoss.GetHtmlFromRazorView(documentTemplate.HeaderCsHtml, documentTemplate.InvoicePdfGenerationDetails); } if (!string.IsNullOrWhiteSpace(documentTemplate.BodyCsHtml)) { // Getting the body Html bodyHtml = RazorBoss.GetHtmlFromRazorView(documentTemplate.BodyCsHtml, documentTemplate.InvoicePdfGenerationDetails); } if (!string.IsNullOrWhiteSpace(documentTemplate.FooterCsHtml)) { // Getting the footer html footerHtml = RazorBoss.GetHtmlFromRazorView(documentTemplate.FooterCsHtml, documentTemplate.InvoicePdfGenerationDetails); } // Getting the blob data based on generated html and template option for file creation byte[] blob = CreatePDFBasedOnHTMLTemplate(headerHtml, bodyHtml, footerHtml, templateOption); // Creating the file stream object and writing to the file objFileStream = new FileStream(filePathToSave, FileMode.Create); objFileStream.Write(blob, 0, blob.Length); return(true); } catch (Exception ex) { MessageBox.Show("Error : " + ex.InnerException.Message); throw; } finally { // Closing and disposing the file stream object if (objFileStream != null) { objFileStream.Close(); objFileStream.Dispose(); } } }
private GenerateResult ProcessPartitionCodeFile(PartitionDefinition part, TemplateHost host, object schema, object profile, TemplateOption option, string content) { if (host.Errors.HasErrors) { var sb = new StringBuilder(); sb.AppendLine("生成 " + (schema ?? "全局") + " 的 " + part.Name + " 时出错。"); foreach (CompilerError error in host.Errors) { sb.AppendLine(error.ErrorText); } Console.WriteLine(sb.ToString()); MessageBoxHelper.ShowError(sb.ToString()); return(null); } else { var result = new GenerateResult(part, content); if (option.WriteToDisk && result.WriteToDisk) { PartitionWriter.Write(result, schema, profile, option.OutputDirectory); } return(result); } }
private List <GenerateResult> GenerateInternal(TemplateOption option, List <Table> tables, CodeGenerateHandler handler) { var result = new List <GenerateResult>(); var _tables = ProxyBuilder.Rebuild(tables); var _profile = ProxyBuilder.Rebuild(option.Profile); var _guids = new GuidDispatcher(); var _reference = new List <dynamic>(); foreach (var table in _tables) { _reference.AddRange(table.ForeignKeys); } var assemblyList = option.DynamicAssemblies; assemblyList.AddRange(ProxyBuilder.GetAssemblyList()); var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "templates\\T4"); var host = new TemplateHost(path, _tables, _reference, assemblyList, _guids); var engine = new Engine(); host.Profile = _profile; var tparts = option.Partitions.Where(s => s.Loop == PartitionLoop.Tables).ToList(); var nparts = option.Partitions.Where(s => s.Loop == PartitionLoop.None).ToList(); var count = tparts.Count * tables.Count + nparts.Count; var index = 0; var calc = new Func <int, int>(i => { return((int)((i / (count * 1.0)) * 100)); }); foreach (var table in _tables) { if (Processor.IsCancellationRequested()) { break; } foreach (var part in tparts) { if (Processor.IsCancellationRequested()) { break; } host.TemplateFile = part.FilePath; if (handler != null) { handler(table.Name, calc(++index)); } host.Current = table; var content = engine.ProcessTemplate(part.Content, host); var r = ProcessPartitionCodeFile(part, host, table, _profile, option, content); if (r != null) { result.Add(r); } } } foreach (var part in nparts) { if (Processor.IsCancellationRequested()) { break; } if (handler != null) { handler("全局", calc(++index)); } host.TemplateFile = part.FilePath; var content = engine.ProcessTemplate(part.Content, host); var r = ProcessPartitionCodeFile(part, host, null, _profile, option, content); if (r != null) { result.Add(r); } } if (option.WriteToDisk) { ResourceWriter.Write(option.Template, option.Profile, option.OutputDirectory); } return(result); }
/// <summary> /// updates the html header based on html content /// </summary> /// <param name="pdfDocumentControl"></param> /// <param name="headerHtml"></param> /// <param name="baseUri"></param> /// <param name="templateOption"></param> private void SetHeader(PdfDocumentControl pdfDocumentControl, string headerHtml, string baseUri, TemplateOption templateOption = null) { PdfHtml headerPdfHtml = new PdfHtml(headerHtml, baseUri); pdfDocumentControl.Header.Enabled = true; float pdfPageWidth = 0, headerWidth = 0, headerHeight = 0; if (templateOption != null) { if (templateOption.HeaderHeight.HasValue) { pdfDocumentControl.Header.Height = templateOption.HeaderHeight.Value; } pdfPageWidth = pdfDocumentControl.PageOrientation == PdfPageOrientation.Portrait ? pdfDocumentControl.PageSize.Width : pdfDocumentControl.PageSize.Height; headerWidth = pdfPageWidth - pdfDocumentControl.Margins.Left - pdfDocumentControl.Margins.Right; headerHeight = pdfDocumentControl.Header.Height; PdfLine leftLine = new PdfLine(new System.Drawing.PointF(leftStartXPoint, 10), new System.Drawing.PointF(leftStartXPoint, headerHeight)); PdfLine rightLine = new PdfLine(new System.Drawing.PointF((float)(headerWidth - 2.5), 10), new System.Drawing.PointF((float)(headerWidth - 2.5), headerHeight)); PdfLine topLine = new PdfLine(new System.Drawing.PointF(leftStartXPoint, 10), new System.Drawing.PointF((float)(headerWidth - 2.5), 10)); //Border Color for the PDF if (!string.IsNullOrEmpty(templateOption.PageMargin.Color)) { leftLine.ForeColor = System.Drawing.Color.FromName(templateOption.PageMargin.Color); leftLine.BackColor = System.Drawing.Color.FromName(templateOption.PageMargin.Color); rightLine.ForeColor = System.Drawing.Color.FromName(templateOption.PageMargin.Color); rightLine.BackColor = System.Drawing.Color.FromName(templateOption.PageMargin.Color); topLine.ForeColor = System.Drawing.Color.FromName(templateOption.PageMargin.Color); topLine.BackColor = System.Drawing.Color.FromName(templateOption.PageMargin.Color); } pdfDocumentControl.Header.Layout(leftLine); pdfDocumentControl.Header.Layout(rightLine); pdfDocumentControl.Header.Layout(topLine); } // add page numbering in a text element System.Drawing.Font pageNumberingFont = new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 8, System.Drawing.GraphicsUnit.Point); PdfText pageNumberingText = new PdfText(headerWidth - 60, 0, "Page {CrtPage} of {PageCount}", pageNumberingFont); pageNumberingText.EmbedSystemFont = true; pdfDocumentControl.Header.Layout(pageNumberingText); pdfDocumentControl.Header.Layout(headerPdfHtml); }
public bool CreateHtmlBasedOnCsHtmlTemplate(DocumentTemplate documentTemplate, string filePathToSave, TemplateOption templateOption = null) { FileStream objFileStream = null; try { string headerHtml = string.Empty; string bodyHtml = string.Empty; string footerHtml = string.Empty; documentTemplate.InvoicePdfGenerationDetails = new InvoicePdfGenerationDetails() { ImagesFolderRootPath = "" }; if (!string.IsNullOrWhiteSpace(documentTemplate.HeaderCsHtml)) { // Getting the header html headerHtml = RazorBoss.GetHtmlFromRazorView(documentTemplate.HeaderCsHtml, documentTemplate.InvoicePdfGenerationDetails); } if (!string.IsNullOrWhiteSpace(documentTemplate.BodyCsHtml)) { // Getting the body Html bodyHtml = RazorBoss.GetHtmlFromRazorView(documentTemplate.BodyCsHtml, documentTemplate.InvoicePdfGenerationDetails); } if (!string.IsNullOrWhiteSpace(documentTemplate.FooterCsHtml)) { // Getting the footer html footerHtml = RazorBoss.GetHtmlFromRazorView(documentTemplate.FooterCsHtml, documentTemplate.InvoicePdfGenerationDetails); } // We write out html here : StringBuilder buffer = new StringBuilder(); buffer.Append("<Html><head></head><body>"); buffer.Append(headerHtml); buffer.Append(bodyHtml); buffer.Append(footerHtml); buffer.Append("</body></Html>"); // we get html byte[] blob = Encoding.ASCII.GetBytes(buffer.ToString()); // Creating the file stream object and writing to the file objFileStream = new FileStream(filePathToSave, FileMode.Create); objFileStream.Write(blob, 0, blob.Length); return(true); } catch (Exception ex) { MessageBox.Show("Error : " + ex.InnerException.Message); throw; } finally { // Closing and disposing the file stream object if (objFileStream != null) { objFileStream.Close(); objFileStream.Dispose(); } } }
/// <summary> /// Updates the footer based on html content /// </summary> /// <param name="pdfDocumentControl"></param> /// <param name="footerHtml"></param> /// <param name="baseUri"></param> /// <param name="templateOption"></param> private void SetFooter(PdfDocumentControl pdfDocumentControl, string footerHtml, string baseUri, TemplateOption templateOption = null) { PdfHtml footerPdfHtml = new PdfHtml(footerHtml, baseUri); pdfDocumentControl.Footer.Enabled = true; if (templateOption != null) { if (templateOption.FooterHeight.HasValue) { pdfDocumentControl.Footer.Height = templateOption.FooterHeight.Value; } if (templateOption.PageMargin != null) { PageBorder pageBorder = templateOption.PageMargin; float pdfPageWidth = pdfDocumentControl.PageOrientation == PdfPageOrientation.Portrait ? pdfDocumentControl.PageSize.Width : pdfDocumentControl.PageSize.Height; float footerWidth = pdfPageWidth - pdfDocumentControl.Margins.Left - pdfDocumentControl.Margins.Right; float footerHeight = pdfDocumentControl.Footer.Height; PdfLine leftLine = new PdfLine(new System.Drawing.PointF(leftStartXPoint, 0), new System.Drawing.PointF(leftStartXPoint, footerHeight)); PdfLine rightLine = new PdfLine(new System.Drawing.PointF((float)(footerWidth - 2.5), 0), new System.Drawing.PointF((float)(footerWidth - 2.5), footerHeight)); PdfLine bottomLine = new PdfLine(new System.Drawing.PointF(leftStartXPoint, footerHeight), new System.Drawing.PointF((float)(footerWidth - 2.5), footerHeight)); //Border Color for the PDF if (!string.IsNullOrEmpty(templateOption.PageMargin.Color)) { leftLine.ForeColor = System.Drawing.Color.FromName(templateOption.PageMargin.Color); leftLine.BackColor = System.Drawing.Color.FromName(templateOption.PageMargin.Color); rightLine.ForeColor = System.Drawing.Color.FromName(templateOption.PageMargin.Color); rightLine.BackColor = System.Drawing.Color.FromName(templateOption.PageMargin.Color); bottomLine.ForeColor = System.Drawing.Color.FromName(templateOption.PageMargin.Color); bottomLine.BackColor = System.Drawing.Color.FromName(templateOption.PageMargin.Color); } pdfDocumentControl.Footer.Layout(leftLine); pdfDocumentControl.Footer.Layout(rightLine); pdfDocumentControl.Footer.Layout(bottomLine); } } pdfDocumentControl.Footer.Layout(footerPdfHtml); }
private void BuildCode() { if (frmTable == null) { MessageBoxHelper.ShowExclamation("你还没有选择要生成的对象,请从【数据源】菜单中选择或配置。"); return; } TemplateDefinition template = null; if (StaticUnity.TemplateProvider == null || (template = StaticUnity.Template) == null) { MessageBoxHelper.ShowExclamation("你还没有选择生成模板,请从【模板】菜单中选择。"); return; } var option = new TemplateOption(); option.Template = template; option.DynamicAssemblies.AddRange(StaticUnity.DynamicAssemblies); option.Profile = StaticUnity.Profile; option.WriteToDisk = true; using (var frm = new frmPreBuild { Template = StaticUnity.Template }) { if (frm.ShowDialog() != DialogResult.OK) { return; } option.Partitions = frm.Partitions; option.OutputDirectory = Config.Instance.OutputDirectory; } spbar.Value = 0; spbar.Visible = true; var time = Processor.Run(this, () => { var tables = frmTable.GetCheckedTables(); StaticUnity.TemplateProvider.GenerateFiles(option, tables, (s, p) => { Invoke(new Action(() => { spState.Text = string.Format("{0}%,正在生成 {1} 的代码文件...", p, s); spbar.Value = p; })); }); Invoke(new Action(() => { spState.Text = "就绪"; spbar.Value = 0; spbar.Visible = false; Process.Start(Config.Instance.OutputDirectory); })); }); Console.WriteLine("代码生成完成,耗时 " + time.ToStringEx()); }