/// <summary> /// 导出Pdf /// </summary> /// <param name="data"></param> /// <param name="pdfExporterAttribute"></param> /// <param name="template"></param> /// <typeparam name="T"></typeparam> /// <returns></returns> /// <exception cref="NotImplementedException"></exception> public async Task <byte[]> ExportBytesByTemplate <T>(T data, PdfExporterAttribute pdfExporterAttribute, string template) where T : class { var exporter = new HtmlExporter(); var htmlString = await exporter.ExportByTemplate(data, template); return(await ExportPdf(pdfExporterAttribute, htmlString)); }
/// <summary> /// 根据模板导出bytes /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data"></param> /// <param name="template"></param> /// <returns></returns> public async Task <byte[]> ExportListBytesByTemplate <T>(ICollection <T> data, string template) where T : class { var exporter = new HtmlExporter(); var htmlString = await exporter.ExportListByTemplate(data, template); using (var generatedDocument = new MemoryStream()) { using (var package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document)) { var mainPart = package.MainDocumentPart; if (mainPart == null) { mainPart = package.AddMainDocumentPart(); new Document(new Body()).Save(mainPart); } var converter = new HtmlConverter(mainPart); converter.ParseHtml(htmlString); mainPart.Document.Save(); byte[] byteArray = Encoding.UTF8.GetBytes(htmlString); using (var stream = new MemoryStream(byteArray)) { mainPart.FeedData(stream); } } return(generatedDocument.ToArray()); } }
private bool SavePost() { if (!FormValidation()) { return(false); } //Only exports part of the generated HTML document by RichEditControlDescription.HTMLText var options = new HtmlDocumentExporterOptions(); options.ExportRootTag = ExportRootTag.Body; options.CssPropertiesExportType = CssPropertiesExportType.Inline; options.DefaultCharacterPropertiesExportToCss = false; var exporter = new HtmlExporter(RichEditControlDescription.Model, options); string formattedDescription = exporter.Export(); if (_post == null) { _post = new Post(Environment.UserName, TitleTextBox.Text, formattedDescription); } else { _post = new Post(_post.Id, _post.Author, TitleTextBox.Text, formattedDescription, _post.LastModifiedTime); } try { try { _dataConnection.AddOrUpdatePost(_post); Close(); } catch (ModifiedByOtherUserException ex) { if (MessageBox.Show(this, "The post was modified by some other user. Do you want to overwrite those changes?", this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) { return(false); } _dataConnection.AddOrUpdatePost(_post, true); Close(); } catch (TitleAlreadyPresentInDBException ex) { MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } } catch (Exception ex) { MessageBox.Show(this, $"Fallimento nell'inserimento del post: {ex.Message}", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return(false); } return(true); }
public static void Register(string settingsFile, string costDataFile, string exportFile = "", EnExportType exportType = EnExportType.Console, IHtmlWrapper wrapper = null) { IMlogger mLogger = new Mlogger(); IAppConfiguration appConfig = new ApplicationConfiguration(settingsFile, costDataFile); TinyIoCContainer.Current.Register <IMlogger>(mLogger); TinyIoCContainer.Current.Register <IAppConfiguration>(appConfig); IDataExporter exporter = null; switch (exportType) { case EnExportType.Console: exporter = new ConsoleWriter(); break; case EnExportType.Csv: exporter = new CsvExporter(mLogger, exportFile); break; case EnExportType.Html: if (wrapper != null) { exporter = new HtmlExporter(mLogger, exportFile, wrapper); } else { // Fall back to Consolewriter - ideally we should log this failure... exporter = new ConsoleWriter(); } break; } TinyIoCContainer.Current.Register <IDataExporter>(exporter); }
private void CopyImages(HtmlExporter htmlExporter, IEnumerable<string> images, string outputPath) { foreach (var image in images) { CopyImage(htmlExporter, image, Path.Combine(outputPath, "images")); } }
public async Task ExportReceipt_Test() { var tplPath = Path.Combine(Directory.GetCurrentDirectory(), "TestFiles", "ExportTemplates", "receipt.cshtml"); var tpl = File.ReadAllText(tplPath); var exporter = new HtmlExporter(); var filePath = Path.Combine(Directory.GetCurrentDirectory(), nameof(ExportReceipt_Test) + ".html"); if (File.Exists(filePath)) { File.Delete(filePath); } //此处使用默认模板导出 var result = await exporter.ExportByTemplate(filePath, new ReceiptInfo() { Amount = 22939.43M, Grade = "2019秋", IdNo = "43062619890622xxxx", Name = "张三", Payee = "湖南心莱信息科技有限公司", PaymentMethod = "微信支付", Profession = "运动训练", Remark = "学费", TradeStatus = "已完成", TradeTime = DateTime.Now, UppercaseAmount = "贰万贰仟玖佰叁拾玖圆肆角叁分", Code = "19071800001" }, tpl); result.ShouldNotBeNull(); File.Exists(filePath).ShouldBeTrue(); }
private void _exportHtmlToolStripMenuItem_Click(object sender, EventArgs e) { using (var dialog = new FolderBrowserDialog()) { dialog.Description = "エクスポート先のフォルダを選択してください。"; dialog.RootFolder = Environment.SpecialFolder.Desktop; dialog.ShowNewFolderButton = true; if (dialog.ShowDialog(this) == DialogResult.OK) { EnsureFocusCommited(); var exporter = new HtmlExporter(); Action <EditorCanvas, Memo, MemoInfo> action = (canvas, memo, info) => { var tags = memo.Tags; if (memo.Tags.Count() == 0) { ExportHtml(canvas, exporter, dialog.SelectedPath, "未整理", memo.Title); } else { foreach (var tag in tags) { ExportHtml(canvas, exporter, dialog.SelectedPath, tag.FullName, memo.Title); } } }; var proc = new MemoProcessor(); proc.Process(this, "HTMLのエクスポート", action); } } }
public string GetHtmlForCsxContent(string csxContent, string baseReferencePath = null, bool failOnCompileWarning = false, bool failOnCompileError = true) { var parser = new CSharpParser(); var annotationResult = parser.Parse(csxContent, baseReferencePath); var errors = new List <string>(); foreach (var r in annotationResult.DiagnosticResults) { if (failOnCompileError && r.Severity == Common.DiagnosticSeverity.Error) { errors.Add(r.Message); } if (failOnCompileWarning && r.Severity == Common.DiagnosticSeverity.Warning) { errors.Add(r.Message); } } if (errors.Any()) { throw new CompilationErrorException(errors); } var exportedHtml = new HtmlExporter().ExportAnnotationResult(annotationResult.TextChunks.Cast <IChunk>()); return(exportedHtml); }
/// <summary> /// 根据模板导出列表 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fileName"></param> /// <param name="dataItems"></param> /// <param name="htmlTemplate"></param> /// <returns></returns> public async Task <ExportFileInfo> ExportListByTemplate <T>(string fileName, ICollection <T> dataItems, string htmlTemplate = null) where T : class { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentException(Resource.FileNameMustBeFilled, nameof(fileName)); } var exporter = new HtmlExporter(); var htmlString = await exporter.ExportListByTemplate(dataItems, htmlTemplate); using (var generatedDocument = new MemoryStream()) { using (var package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document)) { var mainPart = package.MainDocumentPart; if (mainPart == null) { mainPart = package.AddMainDocumentPart(); new Document(new Body()).Save(mainPart); } var converter = new HtmlConverter(mainPart); converter.ParseHtml(htmlString); mainPart.Document.Save(); } File.WriteAllBytes(fileName, generatedDocument.ToArray()); var fileInfo = new ExportFileInfo(fileName, "application/vnd.openxmlformats-officedocument.wordprocessingml.document"); return(fileInfo); } }
public async Task <bool> HandleSuccessfulReqeustAsync(HttpContext context, object body, Type type, string tplPath) { var contentType = ""; string filename = DateTime.Now.ToString("yyyyMMddHHmmss"); byte[] result = null; switch (context.Request.Headers["Magicodes-Type"]) { case HttpContentMediaType.XLSXHttpContentMediaType: filename += ".xlsx"; var dt = ToDataTable(body?.ToString()); contentType = HttpContentMediaType.XLSXHttpContentMediaType; var exporter = new ExcelExporter(); result = await exporter.ExportAsByteArray(dt, type); break; case HttpContentMediaType.PDFHttpContentMediaType: filename += ".pdf"; contentType = HttpContentMediaType.PDFHttpContentMediaType; IExportFileByTemplate pdfexporter = new PdfExporter(); var tpl = await File.ReadAllTextAsync(tplPath); var obj = JsonConvert.DeserializeObject(body.ToString(), type); result = await pdfexporter.ExportBytesByTemplate(obj, tpl, type); break; case HttpContentMediaType.HTMLHttpContentMediaType: filename += ".html"; contentType = HttpContentMediaType.HTMLHttpContentMediaType; IExportFileByTemplate htmlexporter = new HtmlExporter(); result = await htmlexporter.ExportBytesByTemplate(JsonConvert.DeserializeObject(body.ToString(), type), await File.ReadAllTextAsync(tplPath), type); break; case HttpContentMediaType.DOCXHttpContentMediaType: filename += ".docx"; contentType = HttpContentMediaType.DOCXHttpContentMediaType; IExportFileByTemplate docxexporter = new WordExporter(); result = await docxexporter.ExportBytesByTemplate(JsonConvert.DeserializeObject(body.ToString(), type), await File.ReadAllTextAsync(tplPath), type); break; } if (contentType != "") { context.Response.Headers.Add("Content-Disposition", $"attachment;filename={filename}"); context.Response.ContentType = contentType; if (result != null) { await context.Response.Body.WriteAsync(result, 0, result.Length); } } else { return(false); } return(true); }
private void CopyImage(HtmlExporter htmlExporter, string imagePath, string outputPath) { if (!String.IsNullOrEmpty(imagePath) && File.Exists(imagePath)) { htmlExporter.ExecuteOnStepMessage(string.Format(htmlExporter.HtmlStrings.CopyingFile, Path.GetFileName(imagePath))); File.Copy(imagePath, Path.Combine(outputPath, Path.GetFileName(imagePath)), true); } }
/// <summary> /// 简单实现 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data"></param> /// <param name="template"></param> /// <returns></returns> public async Task <byte[]> ExportListBytesByTemplate <T>(ICollection <T> data, string template) where T : class { var exporterAttribute = GetExporterAttribute <T>(); var exporter = new HtmlExporter(); var htmlString = await exporter.ExportListByTemplate(data, template); return(await ExportPdf(exporterAttribute, htmlString)); }
/// <summary> /// 根据模板导出 /// </summary> /// <param name="data"></param> /// <param name="template"></param> /// <param name="type"></param> /// <returns></returns> public async Task <byte[]> ExportBytesByTemplate(object data, string template, Type type) { var exporterAttribute = GetExporterAttribute(type); var exporter = new HtmlExporter(); var htmlString = await exporter.ExportByTemplate(data, template, type); return(await ExportPdf(exporterAttribute, htmlString)); }
//private string get_email(decimal ip_id_nhan_vien) //{ // //US_DM_NHAN_VIEN v_us = new US_DM_NHAN_VIEN(ip_id_nhan_vien); // //return v_us.strEMAIL; // return "*****@*****.**"; //} private string ExportHtml() { string stringHtml = String.Empty; HtmlDocumentExporterOptions options = new HtmlDocumentExporterOptions(); options.ExportRootTag = ExportRootTag.Body; options.CssPropertiesExportType = CssPropertiesExportType.Inline; var exporter = new HtmlExporter(this.m_txt_noi_dung.Model, options); return stringHtml = exporter.Export(); }
static void Main(string[] args) { // set our default folder and query names string folderName = null; string queryName = null; string exportFormat = null; // use the arguments from the command line if we got any if (args.Length == 3) { folderName = args[0]; queryName = args[1]; exportFormat = args[2]; } else { throw new ArgumentException("Command line arguments not provided"); } // give our bitly client our access token if there is one (not required) BitlyClient.AccessToken = ConfigurationManager.AppSettings["BitlyAccessToken"]; // grab our team services info var token = ConfigurationManager.AppSettings["TeamServicesPersonalAccessToken"]; var url = ConfigurationManager.AppSettings["TeamServicesCollectionUrl"]; var project = ConfigurationManager.AppSettings["TeamServicesProjectName"]; // make sure we have the necessary info if (string.IsNullOrEmpty(token) == true || string.IsNullOrEmpty(url) == true || string.IsNullOrEmpty(project) == true) { Console.WriteLine("You must set the Team Services Personal Access Token, Colection URL, and project name in the App.config"); return; } // create our team services client var client = new TeamServicesClient(url, token, project); // retrieve the result set for the given query var result = client.RunQuery(folderName, queryName); // shorten the urls in the items BitlyClient.ShortenUrls(result.Items); // export the query results switch (exportFormat) { case "csv": CsvExporter.ExportItems(queryName, result); break; case "html": HtmlExporter.ExportItems(queryName, result); break; } }
public override void ProcessStep(HtmlExporter htmlExporter) { htmlExporter.ExecuteOnStepProgress(50); CreateHtml(htmlExporter, htmlExporter.Repository, htmlExporter.CurrentStrings, htmlExporter.CurrentLanguage, htmlExporter.OutputPath); htmlExporter.ExecuteOnStepProgress(100); htmlExporter.CurrentStep = null; }
public override void ProcessStep(HtmlExporter htmlExporter) { htmlExporter.ExecuteOnStepProgress(40); CopyAssets(htmlExporter, Path.Combine(Path.GetDirectoryName(this.GetType().Assembly.Location), "assets"), htmlExporter.OutputPath); CopyImages(htmlExporter, htmlExporter.Repository.Images, htmlExporter.OutputPath); CopyImage(htmlExporter, htmlExporter.Repository.ProjectInfo.LogoPath, htmlExporter.OutputPath); htmlExporter.CurrentStep = new CreateHtmlStep(); }
public async Task ExportHtml_Test() { var exporter = new HtmlExporter(); var filePath = Path.Combine(Directory.GetCurrentDirectory(), nameof(ExportHtml_Test) + ".html"); if (File.Exists(filePath)) File.Delete(filePath); //此处使用默认模板导出 var result = await exporter.ExportListByTemplate(filePath, GenFu.GenFu.ListOf<ExportTestData>()); result.ShouldNotBeNull(); File.Exists(filePath).ShouldBeTrue(); }
private void ExportHtml(EditorCanvas canvas, HtmlExporter exporter, string rootPath, string tagFullName, string memoTitle) { var dirPath = Path.Combine(rootPath, PathUtil.GetValidRelativePath(tagFullName, "_")); dirPath = Path.Combine(dirPath, PathUtil.GetValidFilename(memoTitle, "_")); dirPath = Path.GetFullPath(dirPath); dirPath = PathUtil.GetUniqueDirectoryPathByCounting(dirPath); PathUtil.EnsureDirectoryExists(dirPath); exporter.Export(dirPath, canvas); }
public void ExportLastMonthOrders(String fileName) { LastMonthOrders = new ObservableCollection <Order>(barService.OrdersInCurrentMonth()); string htmlExport = HtmlExporter.ExportToHtml(new Dictionary <string, ICollection <IExportable> >() { { "Orders in last month", new List <IExportable>(LastMonthOrders) } }, "Orders in last month"); File.WriteAllText(fileName, htmlExport); }
private void ExportHtml(out string stringHtml, HtmlExporter exporter, string fileName) { stringHtml = String.Empty; HtmlDocumentExporterOptions options = new HtmlDocumentExporterOptions(); options.ExportRootTag = htmlExportType; options.CssPropertiesExportType = cssExportType; options.TargetUri = Path.GetFileNameWithoutExtension(fileName); exporter = new HtmlExporter(this.richEditControl1.Model, options); stringHtml = exporter.Export(); }
//private string get_email(decimal ip_id_nhan_vien) //{ // //US_DM_NHAN_VIEN v_us = new US_DM_NHAN_VIEN(ip_id_nhan_vien); // //return v_us.strEMAIL; // return "*****@*****.**"; //} private string ExportHtml() { string stringHtml = String.Empty; HtmlDocumentExporterOptions options = new HtmlDocumentExporterOptions(); options.ExportRootTag = ExportRootTag.Body; options.CssPropertiesExportType = CssPropertiesExportType.Inline; var exporter = new HtmlExporter(this.m_txt_noi_dung.Model, options); return(stringHtml = exporter.Export()); }
private void CopyTextAndHtml(IEnumerable <IEditor> editors, IDataObject dataObj) { var textExporter = new PlainTextExporter(); dataObj.SetData(DataFormats.UnicodeText, textExporter.ExportText(editors)); var htmlExporter = new HtmlExporter(); var html = htmlExporter.ExportHtml(editors); dataObj.SetData(DataFormats.Html, ClipboardUtil.GetCFHtmlMemoryStream(html)); }
public static string HtmlToRtf(this RichEditControl richEditControl, string markup) { HtmlDocumentExporterOptions options = new HtmlDocumentExporterOptions(); options.ExportRootTag = ExportRootTag.Body; options.CssPropertiesExportType = CssPropertiesExportType.Inline; HtmlExporter exporter = new HtmlExporter(richEditControl.Model, options); string stringHtml = exporter.Export(); return(stringHtml); }
public override void ProcessStep(HtmlExporter htmlExporter) { htmlExporter.ExecuteOnStepProgress(5); htmlExporter.ExecuteOnStepMessage(htmlExporter.HtmlStrings.CreatingNavigation); CreateIndexNav(htmlExporter.Repository, htmlExporter.CurrentStrings, htmlExporter.CurrentLanguage, htmlExporter.OutputPath); htmlExporter.ExecuteOnStepProgress(10); CreateNamespaceNavs(htmlExporter.Repository, htmlExporter.CurrentStrings, htmlExporter.OutputPath); htmlExporter.ExecuteOnStepProgress(15); CreateArticleNavs(htmlExporter.Repository, htmlExporter.CurrentStrings, htmlExporter.CurrentLanguage, htmlExporter.OutputPath); htmlExporter.CurrentStep = new CreateArticleStep(); }
public override void ProcessStep(HtmlExporter htmlExporter) { htmlExporter.ExecuteOnStepProgress(0); htmlExporter.ExecuteOnStepMessage(htmlExporter.HtmlStrings.CreatingFolders); CreateFolder(htmlExporter.OutputPath, "namespace"); CreateFolder(htmlExporter.OutputPath, "type"); CreateFolder(htmlExporter.OutputPath, "constructor"); CreateFolder(htmlExporter.OutputPath, "method"); CreateFolder(htmlExporter.OutputPath, "field"); CreateFolder(htmlExporter.OutputPath, "property"); CreateFolder(htmlExporter.OutputPath, "event"); CreateFolder(htmlExporter.OutputPath, "article"); CreateFolder(htmlExporter.OutputPath, "nav"); htmlExporter.CurrentStep = new CreateNavigationStep(); }
public async Task ExportHtmlBytesByTemplate_Test() { var tplPath = Path.Combine(Directory.GetCurrentDirectory(), "TestFiles", "ExportTemplates", "tpl1.cshtml"); var tpl = File.ReadAllText(tplPath); var exporter = new HtmlExporter(); var filePath = Path.Combine(Directory.GetCurrentDirectory(), nameof(ExportHtmlBytesByTemplate_Test) + ".html"); if (File.Exists(filePath)) File.Delete(filePath); //此处使用默认模板导出 var result = await exporter.ExportListBytesByTemplate( GenFu.GenFu.ListOf<ExportTestData>(), tpl); result.ShouldNotBeNull(); using (var file = File.OpenWrite(filePath)) { file.Write(result, 0, result.Length); } File.Exists(filePath).ShouldBeTrue(); }
private void CopyAssets(HtmlExporter htmlExporter, string input, string output) { foreach (var dir in Directory.EnumerateDirectories(input)) { if (!Directory.Exists(Path.Combine(output, Path.GetFileName(dir)))) { Directory.CreateDirectory(Path.Combine(output, Path.GetFileName(dir))); } var files = Directory.EnumerateFiles(dir); foreach (var file in files) { htmlExporter.ExecuteOnStepMessage(string.Format(htmlExporter.HtmlStrings.CopyingFile, Path.GetFileName(file))); File.Copy(file, Path.Combine(output, Path.GetFileName(dir), Path.GetFileName(file)), true); } CopyAssets(htmlExporter, dir, Path.Combine(output, Path.GetFileName(dir))); } }
public FileResult Download(int implementationGuideId, int[] templateIds, bool inferred) { var ig = this.tdb.ImplementationGuides.Single(y => y.Id == implementationGuideId); // Get the data from the API controller HtmlExporter exporter = new HtmlExporter(this.tdb, true); var dataModel = exporter.GetExportData(implementationGuideId, null, templateIds, inferred); // Serialize the data to JSON var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); jsonSerializer.MaxJsonLength = Int32.MaxValue; var dataContent = jsonSerializer.Serialize(dataModel); var downloadPackage = GetDownloadPackage(ig, dataContent); return(File(downloadPackage.Content, MediaTypeNames.Application.Zip, downloadPackage.FileName)); }
/// <summary> /// 根据模板导出 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fileName"></param> /// <param name="data"></param> /// <param name="htmlTemplate"></param> /// <returns></returns> public async Task <ExportFileInfo> ExportByTemplate <T>(string fileName, T data, string htmlTemplate) where T : class { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentException("文件名必须填写!", nameof(fileName)); } var exporterAttribute = GetExporterAttribute <T>(); var exporter = new HtmlExporter(); var htmlString = await exporter.ExportByTemplate(data, htmlTemplate); if (exporterAttribute.IsWriteHtml) { File.WriteAllText(fileName + ".html", htmlString); } return(await ExportPdf(fileName, exporterAttribute, htmlString)); }
void ExportHtml_Click(object sender, RoutedEventArgs e) { //what to export bool inclAllPersons = eIncludeAllPeople.IsChecked == true, inclCatPersons = eIncludeCatPeople.IsChecked == true, inclTasks = eIncludeSchedule.IsChecked == true, inclNotes = eIncludeNotes.IsChecked == true, inclPasswords = eIncludePasswords.IsChecked == true; //abort if not rational string message = null; if (inclCatPersons && CatId == null) { message = "Select a category before exporting"; } if (inclAllPersons && inclCatPersons) { message = "Choose one type of person export, not both"; } if (!inclAllPersons && !inclCatPersons && !inclTasks && !inclNotes) { message = "Select something to export"; } if (message != null) { VisualUtils.ShowMessageDialog(message); return; } //get filename string filename = AskForExportFileName(true); if (filename == null) { return; } //export HtmlExporter.ExportHtml(filename, inclAllPersons, inclCatPersons ? CatId : null, inclTasks, inclNotes, inclPasswords); VisualUtils.ShowMessageDialog("Export complete"); }
public override void ProcessStep(HtmlExporter htmlExporter) { htmlExporter.ExecuteOnStepProgress(20); if (htmlExporter.Repository.Articles.Count > 0) { var articles = htmlExporter.Repository.Articles.ContainsKey(htmlExporter.CurrentLanguage) ? htmlExporter.Repository.Articles[htmlExporter.CurrentLanguage] : htmlExporter.Repository.Articles["default"]; foreach (var article in articles) { htmlExporter.ExecuteOnStepMessage(string.Format(htmlExporter.HtmlStrings.CreatingArticle, article.Title)); CreateArticle(article, htmlExporter.Repository, htmlExporter.CurrentStrings, htmlExporter.OutputPath); } } htmlExporter.CurrentStep = new CopyStep(); }
private void _saveAsHtmlToolStripMenuItem_Click(object sender, EventArgs e) { if (_currentEditorCanvas == null) { return; } using (var dialog = new FolderBrowserDialog()) { dialog.Description = "保存先のフォルダを選択してください。"; dialog.RootFolder = Environment.SpecialFolder.Desktop; dialog.ShowNewFolderButton = true; if (dialog.ShowDialog(this) == DialogResult.OK) { EnsureFocusCommited(); var exporter = new HtmlExporter(); exporter.Export(dialog.SelectedPath, _EditorCanvas); } } }
/// <summary> /// Throws `CompilationErrorException` when a compilation issue arises. /// </summary> public string GetHtmlForMarkdownContent( string mdContent, string baseReferencePath = null, bool failOnCompileWarning = false, bool failOnCompileError = true) { var sourceDocument = new SourceDocument(mdContent); var(codePart, lineNumberTranslation) = sourceDocument.GetCodeDocument(); var parser = new CSharpParser(); var annotationResult = parser.Parse(codePart.ToString(), baseReferencePath); var errors = new List <string>(); foreach (var r in annotationResult.DiagnosticResults) { if (failOnCompileError && r.Severity == Common.DiagnosticSeverity.Error) { errors.Add(r.Message); } if (failOnCompileWarning && r.Severity == Common.DiagnosticSeverity.Warning) { errors.Add(r.Message); } } if (errors.Any()) { throw new CompilationErrorException(errors); } var compilationResult = annotationResult.TextChunks.Cast <IChunk>().ToList(); SourceDocument.FixLineNumbers(compilationResult, lineNumberTranslation); var allChunks = SourceDocument.ReturnMdChunksIntoCompilationResults(compilationResult, sourceDocument.MarkDownBlocks.ToList()); var exportedHtml = new HtmlExporter().ExportAnnotationResult(allChunks); return(exportedHtml); }
/// <summary> /// 根据模板导出列表 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fileName"></param> /// <param name="dataItems"></param> /// <param name="htmlTemplate"></param> /// <returns></returns> public async Task <TemplateFileInfo> ExportListByTemplate <T>(string fileName, ICollection <T> dataItems, string htmlTemplate = null) where T : class { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentException("文件名必须填写!", nameof(fileName)); } var exporter = new HtmlExporter(); var htmlString = await exporter.ExportListByTemplate(dataItems, htmlTemplate); var converter = new BasicConverter(new PdfTools()); var doc = new HtmlToPdfDocument { GlobalSettings = { ColorMode = ColorMode.Color, Orientation = Orientation.Landscape, PaperSize = PaperKind.A4, Out = fileName, }, Objects = { new ObjectSettings { PagesCount = true, HtmlContent = htmlString, WebSettings = { DefaultEncoding = "utf-8" }, HeaderSettings ={ FontSize =9, Right = "[page]/[toPage]", Line = true, Spacing = 2.812 }, Encoding = System.Text.Encoding.UTF8 } } }; converter.Convert(doc); var fileInfo = new TemplateFileInfo(fileName, "application/pdf"); return(fileInfo); }
private static int handleExportHtml(MonoCovOptions opts,string[] args) { if (args.Length == 0) { Console.WriteLine("Error: Datafile name is required when using --export-html"); return(1); } if (!Directory.Exists(opts.exportHtmlDir)) { try { Directory.CreateDirectory(opts.exportHtmlDir); } catch (Exception ex) { Console.WriteLine("Error: Destination directory '" + opts.exportHtmlDir + "' does not exist and could not be created: " + ex); return(1); } } CoverageModel model = new CoverageModel(); model.ReadFromFile(args [0]); HtmlExporter exporter = new HtmlExporter(); exporter.DestinationDir = opts.exportHtmlDir; exporter.StyleSheet = opts.styleSheet; if (!opts.quiet) { exporter.Progress += new HtmlExporter.ProgressEventHandler(htmlProgressListener); } exporter.Export(model); if (!opts.quiet) { Console.WriteLine(); Console.WriteLine("Done."); } return(0); }
/// <summary> /// 根据模板导出 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="fileName"></param> /// <param name="data"></param> /// <param name="htmlTemplate"></param> /// <returns></returns> public async Task <TemplateFileInfo> ExportByTemplate <T>(string fileName, T data, string htmlTemplate) where T : class { if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentException("文件名必须填写!", nameof(fileName)); } var exporterAttribute = GetExporterAttribute <T>(); var exporter = new HtmlExporter(); var htmlString = await exporter.ExportByTemplate(data, htmlTemplate); if (exporterAttribute.IsWriteHtml) { File.WriteAllText(fileName + ".html", htmlString); } var doc = GetHtmlToPdfDocumentByExporterAttribute(fileName, exporterAttribute, htmlString); PdfConverter.Convert(doc); var fileInfo = new TemplateFileInfo(fileName, "application/pdf"); return(fileInfo); }
public abstract void ProcessStep(HtmlExporter htmlExporter);
private void CreateHtml(HtmlExporter htmlExporter, SDRepository repository, IStrings strings, string docLanguage, string outputPath) { var indexTemplate = new IndexTemplate { Repository = repository, Strings = strings, CurrentLanguage = docLanguage }; File.WriteAllText(Path.Combine(outputPath, "index.html"), indexTemplate.TransformText()); var namespaceCount = 0d; var namespaceTotal = repository.GetAllNamespaces().Count; foreach (var nameSpace in repository.GetAllNamespaces()) { htmlExporter.ExecuteOnStepProgress(Convert.ToInt16((namespaceCount / namespaceTotal) * 50) + 50); htmlExporter.ExecuteOnStepMessage(htmlExporter.HtmlStrings.CreateFilesForNamespace + ": " + nameSpace.Fullname); namespaceCount++; var namespaceTemplate = new NamespaceTemplate { Strings = strings, CurrentLanguage = docLanguage, Namespace = nameSpace, Repository = repository }; File.WriteAllText(Path.Combine(outputPath, "namespace", nameSpace.Guid + ".html"), namespaceTemplate.TransformText()); foreach (var type in nameSpace.Types) { type.SortMembers(); var typeTemplate = new TypeTemplate { Strings = strings, CurrentLanguage = type.Documentation.ContainsKey(docLanguage) ? docLanguage : "default", SDType = type, Repository = repository }; File.WriteAllText(Path.Combine(outputPath, "type", type.Guid + ".html"), typeTemplate.TransformText()); foreach (var constructor in type.Constructors) { var memberTemplate = new MemberTemplate { Strings = strings, CurrentLanguage = constructor.Documentation.ContainsKey(docLanguage) ? docLanguage : "default", SDType = type, SDMember = constructor, Repository = repository }; File.WriteAllText(Path.Combine(outputPath, "constructor", constructor.Guid + ".html"), memberTemplate.TransformText()); } foreach (var method in type.Methods) { var memberTemplate = new MemberTemplate { Strings = strings, CurrentLanguage = method.Documentation.ContainsKey(docLanguage) ? docLanguage : "default", SDType = type, SDMember = method, Repository = repository }; File.WriteAllText(Path.Combine(outputPath, "method", method.Guid + ".html"), memberTemplate.TransformText()); } foreach (var field in type.Fields) { var memberTemplate = new MemberTemplate { Strings = strings, CurrentLanguage = field.Documentation.ContainsKey(docLanguage) ? docLanguage : "default", SDType = type, SDMember = field, Repository = repository }; File.WriteAllText(Path.Combine(outputPath, "field", field.Guid + ".html"), memberTemplate.TransformText()); } foreach (var property in type.Properties) { var memberTemplate = new MemberTemplate { Strings = strings, CurrentLanguage = property.Documentation.ContainsKey(docLanguage) ? docLanguage : "default", SDType = type, SDMember = property, Repository = repository }; File.WriteAllText(Path.Combine(outputPath, "property", property.Guid + ".html"), memberTemplate.TransformText()); } foreach (var eve in type.Events) { var memberTemplate = new MemberTemplate { Strings = strings, CurrentLanguage = eve.Documentation.ContainsKey(docLanguage) ? docLanguage : "default", SDType = type, SDMember = eve, Repository = repository }; File.WriteAllText(Path.Combine(outputPath, "event", eve.Guid + ".html"), memberTemplate.TransformText()); } } } }
private static int handleExportHtml(MonoCovOptions opts, string[] args) { if (args.Length == 0) { Console.WriteLine ("Error: Datafile name is required when using --export-html"); return 1; } if (!Directory.Exists (opts.exportHtmlDir)) { try { Directory.CreateDirectory (opts.exportHtmlDir); } catch (Exception ex) { Console.WriteLine ("Error: Destination directory '" + opts.exportHtmlDir + "' does not exist and could not be created: " + ex); return 1; } } CoverageModel model = new CoverageModel (); model.ReadFromFile (args [0]); HtmlExporter exporter = new HtmlExporter (); exporter.DestinationDir = opts.exportHtmlDir; exporter.StyleSheet = opts.styleSheet; if (!opts.quiet) exporter.Progress += new HtmlExporter.ProgressEventHandler (htmlProgressListener); exporter.Export (model); if (!opts.quiet) { Console.WriteLine (); Console.WriteLine ("Done."); } return 0; }
private static void htmlProgressListener(object sender, HtmlExporter.ProgressEventArgs e) { Console.Write ("\rExporting Data: " + (e.pos * 100 / e.itemCount) + "%"); }
private void SendSimpleButton_Click(object sender, EventArgs e) { try { if (string.IsNullOrEmpty(toMailTextEdit.Text)) { MessageBox.Show("Please Enter Valid EmailId"); return; } else if (string.IsNullOrEmpty(subjectTextEdit.Text)) { MessageBox.Show("Please Enter Valid Subject"); return; } else if (string.IsNullOrEmpty(termsRichEditControl.Text)) { MessageBox.Show("Please Enter Valid Message"); return; } // company object MailBee.Global.LicenseKey = "MN120-4FA35C0C24043460043189003820-98EF"; splashScreenManager1.ShowWaitForm(); splashScreenManager1.SetWaitFormDescription("Sending Mail..."); Smtp mailer = new Smtp(); SmtpServer server = new SmtpServer(Comp.EmailPass, Comp.SendFrom, Comp.SendPass); string strBody = string.Empty; server.SslMode = SslStartupMode.UseStartTls; server.Port = Convert.ToInt32(Comp.SortName); // Convert.ToInt32(Comp.); mailer.SmtpServers.Add(server); mailer.From.Email = Comp.SendFrom; mailer.Subject = subjectTextEdit.Text; HtmlDocumentExporterOptions options = new HtmlDocumentExporterOptions(); options.ExportRootTag = ExportRootTag.Body; options.CssPropertiesExportType = CssPropertiesExportType.Inline; HtmlExporter exporter = new HtmlExporter(this.termsRichEditControl.Model, options); string stringHtml = exporter.Export(); mailer.BodyHtmlText = stringHtml; if (!string.IsNullOrEmpty(atch1ButtonEdit.Text)) { mailer.Message.Attachments.Add(atch1ButtonEdit.Text); } if (!string.IsNullOrEmpty(atch2ButtonEdit.Text)) { mailer.Message.Attachments.Add(atch2ButtonEdit.Text); } if (!string.IsNullOrEmpty(atch3ButtonEdit.Text)) { mailer.Message.Attachments.Add(atch3ButtonEdit.Text); } if (!string.IsNullOrEmpty(atch4ButtonEdit.Text)) { mailer.Message.Attachments.Add(atch4ButtonEdit.Text); } string[] strparty = toMailTextEdit.Text.Split(';'); foreach (var mail in strparty) { if (!string.IsNullOrEmpty(mail)) { mailer.Message.To.Add(mail); } } if (!string.IsNullOrEmpty(ccMailTextEdit.Text)) { mailer.Cc.Add(ccMailTextEdit.Text); } if (!string.IsNullOrEmpty(bccMailTextEdit.Text)) { mailer.Bcc.Add(bccMailTextEdit.Text); } if (mailer.Send()) { splashScreenManager1.CloseWaitForm(); MessageBox.Show("Email Send Successfully....."); this.Close(); this.Dispose(); } else { splashScreenManager1.CloseWaitForm(); MessageBox.Show("Email Not Sended Successfully"); } } catch (Exception ex) { if (splashScreenManager1.IsSplashFormVisible) { splashScreenManager1.CloseWaitForm(); } Serilog.Log.Error(ex, "Error While Sending Mail"); MessageBox.Show(ex.ToString()); } }
public void GivenANewHtmlExporter() { _exporter = new HtmlExporter(_exportPath, _configuration, new Bootstrapper()); _exporter.Initialise(); }
public HttpResponseMessage Export(ExportSettingsModel model) { ImplementationGuide ig = this.tdb.ImplementationGuides.SingleOrDefault(y => y.Id == model.ImplementationGuideId); if (model.TemplateIds == null) { model.TemplateIds = ig.GetRecursiveTemplates(this.tdb, categories: model.SelectedCategories.ToArray()).Select(y => y.Id).ToList(); } List <Template> templates = this.tdb.Templates.Where(y => model.TemplateIds.Contains(y.Id)).ToList(); SimpleSchema schema = SimplifiedSchemaContext.GetSimplifiedSchema(HttpContext.Current.Application, ig.ImplementationGuideType); IIGTypePlugin igTypePlugin = IGTypePluginFactory.GetPlugin(ig.ImplementationGuideType); IGSettingsManager igSettings = new IGSettingsManager(this.tdb, model.ImplementationGuideId); bool isCDA = ig.ImplementationGuideType.SchemaURI == "urn:hl7-org:v3"; string fileName; byte[] export; string contentType = null; switch (model.ExportFormat) { case ExportFormats.FHIR_Build_Package: case ExportFormats.FHIR_Bundle: case ExportFormats.Native_XML: case ExportFormats.Templates_DSTU_XML: string fileExtension = model.ReturnJson ? "json" : "xml"; contentType = model.ReturnJson ? JSON_MIME_TYPE : XML_MIME_TYPE; if (model.ExportFormat == ExportFormats.FHIR_Build_Package) { fileExtension = "zip"; contentType = ZIP_MIME_TYPE; } fileName = string.Format("{0}.{1}", ig.GetDisplayName(true), fileExtension); var pluginExporter = igTypePlugin.GetExporter(); export = pluginExporter.Export(this.tdb, schema, model.ExportFormat, igSettings, model.SelectedCategories, templates, model.IncludeVocabulary, model.ReturnJson); break; case ExportFormats.Snapshot_JSON: ImplementationGuideController ctrl = new ImplementationGuideController(this.tdb); var dataModel = ctrl.GetViewData(model.ImplementationGuideId, null, null, true); // Serialize the data to JSON var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer(); jsonSerializer.MaxJsonLength = Int32.MaxValue; export = System.Text.Encoding.UTF8.GetBytes(jsonSerializer.Serialize(dataModel)); // Set the filename to JSON fileName = string.Format("{0}.json", ig.GetDisplayName(true)); contentType = JSON_MIME_TYPE; break; case ExportFormats.Microsoft_Word_DOCX: ImplementationGuideGenerator generator = new ImplementationGuideGenerator(this.tdb, model.ImplementationGuideId, model.TemplateIds); fileName = string.Format("{0}.docx", ig.GetDisplayName(true)); ExportSettings lConfig = new ExportSettings(); lConfig.Use(c => { c.GenerateTemplateConstraintTable = model.TemplateTables == TemplateTableOptions.ConstraintOverview || model.TemplateTables == TemplateTableOptions.Both; c.GenerateTemplateContextTable = model.TemplateTables == TemplateTableOptions.Context || model.TemplateTables == TemplateTableOptions.Both; c.GenerateDocTemplateListTable = model.DocumentTables == DocumentTableOptions.List || model.DocumentTables == DocumentTableOptions.Both; c.GenerateDocContainmentTable = model.DocumentTables == DocumentTableOptions.Containment || model.DocumentTables == DocumentTableOptions.Both; c.AlphaHierarchicalOrder = model.TemplateSortOrder == TemplateSortOrderOptions.AlphaHierarchically; c.DefaultValueSetMaxMembers = model.ValueSetTables ? model.MaximumValueSetMembers : 0; c.GenerateValueSetAppendix = model.ValueSetAppendix; c.IncludeXmlSamples = model.IncludeXmlSample; c.IncludeChangeList = model.IncludeChangeList; c.IncludeTemplateStatus = model.IncludeTemplateStatus; c.IncludeNotes = model.IncludeNotes; c.IncludeVolume1 = model.IncludeVolume1; c.SelectedCategories = model.SelectedCategories; c.GenerateRequiredAndOptionalSectionsTable = model.GenerateRequiredAndOptionalSectionsTable; c.DocumentTemplateTypeId = model.DocumentTemplateTypeId; c.SectionTemplateTypeId = model.SectionTemplateTypeId; }); if (model.ValueSetOid != null && model.ValueSetOid.Count > 0) { Dictionary <string, int> valueSetMemberMaximums = new Dictionary <string, int>(); for (int i = 0; i < model.ValueSetOid.Count; i++) { if (valueSetMemberMaximums.ContainsKey(model.ValueSetOid[i])) { continue; } valueSetMemberMaximums.Add(model.ValueSetOid[i], model.ValueSetMaxMembers[i]); } lConfig.ValueSetMaxMembers = valueSetMemberMaximums; } generator.BuildImplementationGuide(lConfig, ig.ImplementationGuideType.GetPlugin()); export = generator.GetDocument(); contentType = DOCX_MIME_TYPE; break; case ExportFormats.Schematron_SCH: string schematronResult = SchematronGenerator.Generate(tdb, ig, model.IncludeCustomSchematron, VocabularyOutputType.Default, model.VocabularyFileName, templates, model.SelectedCategories, model.DefaultSchematron); export = ASCIIEncoding.UTF8.GetBytes(schematronResult); fileName = string.Format("{0}.sch", ig.GetDisplayName(true)); contentType = XML_MIME_TYPE; if (model.IncludeVocabulary) { using (ZipFile zip = new ZipFile()) { zip.AddEntry(fileName, export); NativeTerminologyExporter nativeTermExporter = new NativeTerminologyExporter(this.tdb); byte[] vocData = nativeTermExporter.GetExport(ig.Id, model.MaximumValueSetMembers, this.GetExportEncoding(model)); string vocFileName = string.Format("{0}", model.VocabularyFileName); //Ensuring the extension is present in case input doesn't have it if (vocFileName.IndexOf(".xml") == -1) { vocFileName += ".xml"; } zip.AddEntry(vocFileName, vocData); using (MemoryStream ms = new MemoryStream()) { zip.Save(ms); fileName = string.Format("{0}.zip", ig.GetDisplayName(true)); contentType = ZIP_MIME_TYPE; export = ms.ToArray(); } } } break; case ExportFormats.Vocabulary_XLSX: fileName = string.Format("{0}.xlsx", ig.GetDisplayName(true)); contentType = XLSX_MIME_TYPE; ExcelExporter excelExporter = new ExcelExporter(this.tdb); export = excelExporter.GetSpreadsheet(ig.Id, model.MaximumValueSetMembers); break; case ExportFormats.Vocbulary_Single_SVS_XML: fileName = string.Format("{0}_SingleSVS.xml", ig.GetDisplayName(true)); contentType = XML_MIME_TYPE; SingleSVSExporter ssvsExporter = new SingleSVSExporter(this.tdb); export = ssvsExporter.GetExport(ig.Id, model.MaximumValueSetMembers, this.GetExportEncoding(model)); break; case ExportFormats.Vocabulary_Multiple_SVS_XML: fileName = string.Format("{0}_MultipleSVS.xml", ig.GetDisplayName(true)); contentType = XML_MIME_TYPE; MultipleSVSExporter msvsExporter = new MultipleSVSExporter(this.tdb); export = msvsExporter.GetExport(ig.Id, model.MaximumValueSetMembers, this.GetExportEncoding(model)); break; case ExportFormats.Vocabulary_Native_XML: fileName = string.Format("{0}_MultipleSVS.xml", ig.GetDisplayName(true)); contentType = XML_MIME_TYPE; NativeTerminologyExporter nativeExporter = new NativeTerminologyExporter(this.tdb); export = nativeExporter.GetExport(ig.Id, model.MaximumValueSetMembers, this.GetExportEncoding(model)); break; case ExportFormats.Web_HTML: // Get the data from the API controller HtmlExporter exporter = new HtmlExporter(this.tdb); var templateIds = templates.Select(y => y.Id).ToArray(); var htmlDataModel = exporter.GetExportData(ig.Id, null, templateIds, model.IncludeInferred); IGController igController = new IGController(this.tdb); var downloadPackage = igController.GetDownloadPackage(ig, JsonConvert.SerializeObject(htmlDataModel)); export = downloadPackage.Content; fileName = downloadPackage.FileName; contentType = ZIP_MIME_TYPE; break; case ExportFormats.Vocbulary_Bundle_FHIR_XML: ValueSetExporter vsExporter = new ValueSetExporter(this.tdb); var bundle = vsExporter.GetImplementationGuideValueSets(ig); if (model.ReturnJson) { export = fhir_stu3.Hl7.Fhir.Serialization.FhirSerializer.SerializeResourceToJsonBytes(bundle); fileName = string.Format("{0}_fhir_voc.json", ig.GetDisplayName(true)); contentType = JSON_MIME_TYPE; } else { export = fhir_stu3.Hl7.Fhir.Serialization.FhirSerializer.SerializeResourceToXmlBytes(bundle); fileName = string.Format("{0}_fhir_voc.xml", ig.GetDisplayName(true)); contentType = XML_MIME_TYPE; } break; default: throw new NotSupportedException(); } return(GetExportResponse(fileName, contentType, export)); }