public static void Run() { try { // ExStart:OutPutToStream // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion_PDFToHTMLFormat(); Document doc = new Document( dataDir + "input.pdf"); // Tune conversion params HtmlSaveOptions newOptions = new HtmlSaveOptions(); newOptions.RasterImagesSavingMode = HtmlSaveOptions.RasterImagesSavingModes.AsEmbeddedPartsOfPngPageBackground; newOptions.FontSavingMode = HtmlSaveOptions.FontSavingModes.SaveInAllFormats; newOptions.PartsEmbeddingMode = HtmlSaveOptions.PartsEmbeddingModes.EmbedAllIntoHtml; newOptions.LettersPositioningMethod = HtmlSaveOptions.LettersPositioningMethods.UseEmUnitsAndCompensationOfRoundingErrorsInCss; newOptions.SplitIntoPages = false;// Force write HTMLs of all pages into one output document newOptions.CustomHtmlSavingStrategy = new HtmlSaveOptions.HtmlPageMarkupSavingStrategy(SavingToStream); // We can use some non-existing puth as result file name - all real saving will be done // In our custom method SavingToStream() (it's follows this one) doc.Save(dataDir + "OutPutToStream_out.html", newOptions); // ExEnd:OutPutToStream } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public static void PDFNEWNET_34748() { //----------------------------------------------------- // 1) Tune paths and set license //----------------------------------------------------- (new Aspose.Pdf.License()).SetLicense(@"F:\_Sources\Aspose_5\trunk\testdata\License\Aspose.Total.lic"); Document pdfDocument = new Document(@"F:\ExternalTestsData\34748_36189.pdf"); string outHtmlFile = @"F:\ExternalTestsData\34748.html"; _folderForReferencedResources_34748 = @"F:\ExternalTestsData\out_34748\"; //----------------------------------------------------- // 2) Clean results if they already present //----------------------------------------------------- if (Directory.Exists(_folderForReferencedResources_34748)) { Directory.Delete(_folderForReferencedResources_34748, true); } File.Delete(outHtmlFile); //----------------------------------------------------- // Create HtmlSaveOption with tested feature //----------------------------------------------------- HtmlSaveOptions saveOptions = new HtmlSaveOptions(); saveOptions.CustomResourceSavingStrategy = new HtmlSaveOptions.ResourceSavingStrategy(Strategy_11_CUSTOM_SAVE_OF_FONTS_AND_IMAGES); saveOptions.CustomCssSavingStrategy = new HtmlSaveOptions.CssSavingStrategy(Strategy_11_CSS_WriteCssToPredefinedFolder); saveOptions.CustomStrategyOfCssUrlCreation = new HtmlSaveOptions.CssUrlMakingStrategy(Strategy_11_CSS_ReturnResultPathInPredefinedTestFolder); using (Stream outStream = File.OpenWrite(outHtmlFile)) { pdfDocument.Save(outStream, saveOptions); } }
public static void Run() { try { // ExStart:SingleHTML // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion_PDFToHTMLFormat(); // Load source PDF file Document doc = new Document(dataDir + "input.pdf"); // Instantiate HTML Save options object HtmlSaveOptions newOptions = new HtmlSaveOptions(); // Enable option to embed all resources inside the HTML newOptions.PartsEmbeddingMode = HtmlSaveOptions.PartsEmbeddingModes.EmbedAllIntoHtml; // This is just optimization for IE and can be omitted newOptions.LettersPositioningMethod = HtmlSaveOptions.LettersPositioningMethods.UseEmUnitsAndCompensationOfRoundingErrorsInCss; newOptions.RasterImagesSavingMode = HtmlSaveOptions.RasterImagesSavingModes.AsEmbeddedPartsOfPngPageBackground; newOptions.FontSavingMode = HtmlSaveOptions.FontSavingModes.SaveInAllFormats; // Output file path string outHtmlFile = "SingleHTML_out.html"; doc.Save(outHtmlFile, newOptions); // ExEnd:SingleHTML } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public static void Run() { try { // ExStart:SaveImages // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion_PDFToHTMLFormat(); // Source PDF file Document doc = new Document(dataDir + "input.pdf"); // Create HtmlSaveOption with tested feature HtmlSaveOptions saveOptions = new HtmlSaveOptions(); saveOptions.FixedLayout = true; saveOptions.SplitIntoPages = false; saveOptions.RasterImagesSavingMode = HtmlSaveOptions.RasterImagesSavingModes.AsExternalPngFilesReferencedViaSvg; // Save the output in HTML format doc.Save( dataDir + "SaveImages_out.html", saveOptions); // ExEnd:SaveImages } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private static string CssUrlMakingStrategy(HtmlSaveOptions.CssUrlRequestInfo requestInfo) { string template = "style{0}.css"; // One more example of template : // String template = "http:// Localhost:24661/document-viewer/GetResourceForHtmlHandler?documentPath=Deutschland201207Arbeit.pdf&resourcePath=style{0}.css&fileNameOnly=false"; return template; }
// ExStart:PrefixToImportDirectivesHelper private static void Strategy_10_CSS_WriteCssToResourceFolder(HtmlSaveOptions.CssSavingInfo resourceInfo) { // ------------------------------------------------------- // This is only one of possible implementation of saving // You can write and use Your own implementation if You will // ------------------------------------------------------- // Get CSS file name from requested file. // Some trick required cause we get in parameters of this method // Not pure file name but full URL that // Created with usage of our template returned in Strategy_9_CSS_ReturnResultPathInPredefinedTestFolder() // So, knowing of that template we must extract from it CSS file name itself string guid = System.Guid.NewGuid().ToString(); string fullPathWithGuid = Strategy_10_CSS_ReturnResultPathInPredefinedTestFolder(new HtmlSaveOptions.CssUrlRequestInfo()); fullPathWithGuid = string.Format(fullPathWithGuid, guid); int prefixLength = fullPathWithGuid.IndexOf(guid); int suffixLength = fullPathWithGuid.Length - (fullPathWithGuid.IndexOf(guid) + guid.Length); string fullPath = resourceInfo.SupposedURL; fullPath = fullPath.Substring(prefixLength); string cssFileNameCore = fullPath.Substring(0, fullPath.Length - suffixLength); // Get final file name for saving string cssFileName = "style" + cssFileNameCore + ".css"; string path = _folderForReferencedResources_36435 + cssFileName; // Saving itself System.IO.BinaryReader reader = new BinaryReader(resourceInfo.ContentStream); System.IO.File.WriteAllBytes(path, reader.ReadBytes((int)resourceInfo.ContentStream.Length)); }
public static void Run() { try { // ExStart:PrefixForFonts // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion_PDFToHTMLFormat(); Document doc = new Document(dataDir + "input.pdf"); string outHtmlFile = dataDir + "PrefixForFonts_out.html"; _desiredFontDir = Path.GetDirectoryName(outHtmlFile) + @"\36296_files\"; if (!Directory.Exists(_desiredFontDir)) { Directory.CreateDirectory(_desiredFontDir); } // Reset counter for font names - this counter will be used in our custom code // To generate unigue font file names _fontNumberForUniqueFontFileNames = 0; // Create HtmlSaveOption with custom saving strategy that will do all the job HtmlSaveOptions saveOptions = new HtmlSaveOptions(); saveOptions.CustomResourceSavingStrategy = new HtmlSaveOptions.ResourceSavingStrategy(CustomResourcesProcessing); doc.Save(outHtmlFile, saveOptions); // ExEnd:PrefixForFonts } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public void ExportFonts(bool exportAsBase64) { Document doc = new Document(MyDir + "Document.doc"); HtmlSaveOptions saveOptions = new HtmlSaveOptions { ExportFontResources = true, ExportFontsAsBase64 = exportAsBase64 }; switch (exportAsBase64) { case false: doc.Save(ArtifactsDir + "DocumentExportFonts 1.html", saveOptions); Assert.IsNotEmpty(Directory.GetFiles(ArtifactsDir, "DocumentExportFonts 1.times.ttf", SearchOption.AllDirectories)); break; case true: doc.Save(ArtifactsDir + "DocumentExportFonts 2.html", saveOptions); Assert.IsEmpty(Directory.GetFiles(ArtifactsDir, "DocumentExportFonts 2.times.ttf", SearchOption.AllDirectories)); break; } }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create workbook object and access first worksheet. Workbook wb = new Workbook(); Worksheet ws = wb.Worksheets[0]; // Access cell B4 and add some text inside it. Cell cell = ws.Cells["B4"]; cell.PutValue("This text has some unknown or invalid font which does not exist."); // Set the font of cell B4 which is unknown. Style st = cell.GetStyle(); st.Font.Name = "UnknownNotExist"; st.Font.Size = 20; cell.SetStyle(st); // Now save the workbook in html format and set the default font to Courier New. HtmlSaveOptions opts = new HtmlSaveOptions(); opts.DefaultFontName = "Courier New"; wb.Save(dataDir + "out_courier_new_out.htm", opts); // Now save the workbook in html format once again but set the default font to Arial. opts.DefaultFontName = "Arial"; wb.Save(dataDir + "out_arial_out.htm", opts); // Now save the workbook in html format once again but set the default font to Times New Roman. opts.DefaultFontName = "Times New Roman"; wb.Save(dataDir + "times_new_roman_out.htm", opts); // ExEnd:1 }
public static void Run() { // ExStart:SpecifySaveOption // The path to the documents directory. string dataDir = RunExamples.GetDataDir_LoadingAndSaving(); string fileName = "TestFile RenderShape.docx"; Document doc = new Document(dataDir + fileName); // This is the directory we want the exported images to be saved to. string imagesDir = Path.Combine(dataDir, "Images"); // The folder specified needs to exist and should be empty. if (Directory.Exists(imagesDir)) Directory.Delete(imagesDir, true); Directory.CreateDirectory(imagesDir); // Set an option to export form fields as plain text, not as HTML input elements. HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html); options.ExportTextInputFormFieldAsText = true; options.ImagesFolder = imagesDir; dataDir = dataDir + "Document.SaveWithOptions_out.html"; doc.Save(dataDir, options); // ExEnd:SpecifySaveOption Console.WriteLine("\nSave option specified successfully.\nFile saved at " + dataDir); }
public static void Run() { try { // ExStart:PrefixForURLs // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion_PDFToHTMLFormat(); Document testDoc = new Document(dataDir + "input.pdf"); HtmlSaveOptions options = new HtmlSaveOptions(); // This is main setting that allows work and testing of tested feature options.RasterImagesSavingMode = HtmlSaveOptions.RasterImagesSavingModes.AsExternalPngFilesReferencedViaSvg;// options.CustomResourceSavingStrategy = new HtmlSaveOptions.ResourceSavingStrategy(Custom_processor_of_embedded_images); // Do conversion testDoc.Save(dataDir + @"PrefixForURLs_out.html", options); // ExEnd:PrefixForURLs } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public void CssClassNamesNotValidPrefix() { HtmlSaveOptions saveOptions = new HtmlSaveOptions(); Assert.Throws <ArgumentException>(() => saveOptions.CssClassNamePrefix = "@%-", "The class name prefix must be a valid CSS identifier."); }
public void ConfigForSavingExternalResources() { Document doc = new Document(MyDir + "HtmlSaveOptions.ExportPageMargins.docx"); HtmlSaveOptions saveOptions = new HtmlSaveOptions { CssStyleSheetType = CssStyleSheetType.External, ExportFontResources = true, ResourceFolder = "Resources", ResourceFolderAlias = "https://www.aspose.com/" }; doc.Save(ArtifactsDir + "HtmlSaveOptions.ExportPageMargins.html", saveOptions); string[] imageFiles = Directory.GetFiles(ArtifactsDir + "Resources/", "*.png", SearchOption.AllDirectories); Assert.AreEqual(3, imageFiles.Length); string[] fontFiles = Directory.GetFiles(ArtifactsDir + "Resources/", "*.ttf", SearchOption.AllDirectories); Assert.AreEqual(1, fontFiles.Length); string[] cssFiles = Directory.GetFiles(ArtifactsDir + "Resources/", "*.css", SearchOption.AllDirectories); Assert.AreEqual(1, cssFiles.Length); DocumentHelper.FindTextInFile(ArtifactsDir + "HtmlSaveOptions.ExportPageMargins.html", "<link href=\"https://www.aspose.com/HtmlSaveOptions.ExportPageMargins.css\""); }
public static void Run() { try { // ExStart:PrefixForFonts // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion_PDFToHTMLFormat(); Document doc = new Document(dataDir + "input.pdf"); string outHtmlFile = dataDir + "PrefixForFonts_out_.html"; _desiredFontDir = Path.GetDirectoryName(outHtmlFile) + @"\36296_files\"; if (!Directory.Exists(_desiredFontDir)) { Directory.CreateDirectory(_desiredFontDir); } // Reset counter for font names - this counter will be used in our custom code // to generate unigue font file names _fontNumberForUniqueFontFileNames = 0; // Create HtmlSaveOption with custom saving strategy that will do all the job HtmlSaveOptions saveOptions = new HtmlSaveOptions(); saveOptions.CustomResourceSavingStrategy = new HtmlSaveOptions.ResourceSavingStrategy(CustomResourcesProcessing); doc.Save(outHtmlFile, saveOptions); // ExEnd:PrefixForFonts } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public void ResolveFontNames() { //ExStart //ExFor:HtmlSaveOptions.ResolveFontNames //ExSummary:Shows how to resolve all font names before writing them to HTML. Document document = new Document(MyDir + "HtmlSaveOptions.ResolveFontNames.docx"); FontSettings fontSettings = new FontSettings { SubstitutionSettings = { DefaultFontSubstitution = { DefaultFontName = "Arial", Enabled = true } } }; document.FontSettings = fontSettings; HtmlSaveOptions saveOptions = new HtmlSaveOptions(SaveFormat.Html) { // By default this option is set to 'False' and Aspose.Words writes font names as specified in the source document ResolveFontNames = true }; document.Save(ArtifactsDir + "HtmlSaveOptions.ResolveFontNames.html", saveOptions); //ExEnd DocumentHelper.FindTextInFile(ArtifactsDir + "HtmlSaveOptions.ResolveFontNames.html", "<span style=\"font-family:Arial\">"); }
public static void Run() { try { // ExStart:SaveImages // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion_PDFToHTMLFormat(); // Source PDF file Document doc = new Document(dataDir + "input.pdf"); // Create HtmlSaveOption with tested feature HtmlSaveOptions saveOptions = new HtmlSaveOptions(); saveOptions.FixedLayout = true; saveOptions.SplitIntoPages = false; saveOptions.RasterImagesSavingMode = HtmlSaveOptions.RasterImagesSavingModes.AsExternalPngFilesReferencedViaSvg; // Save the output in HTML format doc.Save(dataDir + "SaveImages_out.html", saveOptions); // ExEnd:SaveImages } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public static byte[] guardarDocumentoComoHtml(Document docGuardar) { MemoryStream streamSalida = null; byte[] resultadoArchivo = null; try{ streamSalida = new MemoryStream(); HtmlSaveOptions htmlSave = new HtmlSaveOptions() { ExportImagesAsBase64 = true, ExportHeadersFootersMode = ExportHeadersFootersMode.FirstSectionHeaderLastSectionFooter, PrettyFormat = true, CssStyleSheetType = CssStyleSheetType.Inline, Encoding = System.Text.Encoding.UTF8, }; docGuardar.Save(streamSalida, htmlSave); resultadoArchivo = streamSalida.ToArray(); }catch (Exception ex) { throw ex; }finally{ if (streamSalida != null) { streamSalida.Close(); } } return(resultadoArchivo); }
public static void Run() { //ExStart:ConvertDocumentToEPUB // The path to the documents directory. string dataDir = RunExamples.GetDataDir_LoadingAndSaving(); // Load the document from disk. Document doc = new Document(dataDir + "Document.EpubConversion.doc"); // Create a new instance of HtmlSaveOptions. This object allows us to set options that control // how the output document is saved. HtmlSaveOptions saveOptions = new HtmlSaveOptions(); // Specify the desired encoding. saveOptions.Encoding = System.Text.Encoding.UTF8; // Specify at what elements to split the internal HTML at. This creates a new HTML within the EPUB // which allows you to limit the size of each HTML part. This is useful for readers which cannot read // HTML files greater than a certain size e.g 300kb. saveOptions.DocumentSplitCriteria = DocumentSplitCriteria.HeadingParagraph; // Specify that we want to export document properties. saveOptions.ExportDocumentProperties = true; // Specify that we want to save in EPUB format. saveOptions.SaveFormat = SaveFormat.Epub; // Export the document as an EPUB file. doc.Save(dataDir + "Document.EpubConversion_out_.epub", saveOptions); //ExEnd:ConvertDocumentToEPUB ConvertDocumentToEPUBUsingDefaultSaveOption(); Console.WriteLine("\nDocument converted to EPUB successfully."); }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Specify the file path string filePath = dataDir + "Book1.xlsx"; // Load a spreadsheet to be converted Workbook book = new Workbook(filePath); // Create an instance of HtmlSaveOptions HtmlSaveOptions saveOptions = new HtmlSaveOptions(SaveFormat.Html); // Set the ImageFormat to PNG saveOptions.ImageOptions.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; // Set SmoothingMode to AntiAlias saveOptions.ImageOptions.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; // Set TextRenderingHint to AntiAlias saveOptions.ImageOptions.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; // Save spreadsheet to HTML while passing object of HtmlSaveOptions book.Save( dataDir + "output.html", saveOptions); // ExEnd:1 }
[Test] //ExSkip public void DocumentPartsFileNames() { Document doc = new Document(MyDir + "Rendering.docx"); string outFileName = "SavingCallback.DocumentPartsFileNames.html"; // Create an "HtmlFixedSaveOptions" object, which we can pass to the document's "Save" method // to modify how we convert the document to HTML. HtmlSaveOptions options = new HtmlSaveOptions(); // If we save the document normally, there will be one output HTML // document with all of the source document's contents. // Set the "DocumentSplitCriteria" property to "DocumentSplitCriteria.SectionBreak" to // save our document to multiple HTML files: one for each section. options.DocumentSplitCriteria = DocumentSplitCriteria.SectionBreak; // Assign a custom callback to the "DocumentPartSavingCallback" property to alter the document part saving logic. options.DocumentPartSavingCallback = new SavedDocumentPartRename(outFileName, options.DocumentSplitCriteria); // If we convert a document that contains images into html, we will end up with one html file which links to several images. // Each image will be in the form of a file in the local file system. // There is also a callback that can customize the name and file system location of each image. options.ImageSavingCallback = new SavedImageRename(outFileName); doc.Save(ArtifactsDir + outFileName, options); }
public static void Run() { // ExStart:1 // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create your workbook Workbook wb = new Workbook(); // Access first worksheet Worksheet ws = wb.Worksheets[0]; // Fill worksheet with some integer values for (int r = 0; r < 10; r++) { for (int c = 0; c < 10; c++) { ws.Cells[r, c].PutValue(r * 1); } } // Save your workbook in HTML format and export gridlines HtmlSaveOptions opts = new HtmlSaveOptions(); opts.ExportGridLines = true; wb.Save(dataDir + "ExportToHTMLWithGridLines_out.html", opts); // ExEnd:1 }
public ViewResult UploadFile(IFormFile file) { // Set file path var path = Path.Combine("wwwroot/uploads", file.FileName); using (var stream = new FileStream(path, FileMode.Create)) { file.CopyTo(stream); } // Load Word document Document doc = new Document(path); var outStream = new MemoryStream(); // Set HTML options HtmlSaveOptions opt = new HtmlSaveOptions(); opt.ExportImagesAsBase64 = true; opt.ExportFontsAsBase64 = true; // Convert Word document to HTML doc.Save(outStream, opt); // Read text from stream outStream.Position = 0; using (StreamReader reader = new StreamReader(outStream)) { ViewBag.HtmlContent = reader.ReadToEnd(); } return(View("Index")); }
public static void Run() { // ExStart:ConvertDocumentToEPUB // The path to the documents directory. string dataDir = RunExamples.GetDataDir_LoadingAndSaving(); // Load the document from disk. Document doc = new Document(dataDir + "Document.EpubConversion.doc"); // Create a new instance of HtmlSaveOptions. This object allows us to set options that control // How the output document is saved. HtmlSaveOptions saveOptions = new HtmlSaveOptions(); // Specify the desired encoding. saveOptions.Encoding = System.Text.Encoding.UTF8; // Specify at what elements to split the internal HTML at. This creates a new HTML within the EPUB // which allows you to limit the size of each HTML part. This is useful for readers which cannot read // HTML files greater than a certain size e.g 300kb. saveOptions.DocumentSplitCriteria = DocumentSplitCriteria.HeadingParagraph; // Specify that we want to export document properties. saveOptions.ExportDocumentProperties = true; // Specify that we want to save in EPUB format. saveOptions.SaveFormat = SaveFormat.Epub; // Export the document as an EPUB file. doc.Save(dataDir + "Document.EpubConversion_out.epub", saveOptions); // ExEnd:ConvertDocumentToEPUB ConvertDocumentToEPUBUsingDefaultSaveOption(); Console.WriteLine("\nDocument converted to EPUB successfully."); }
public void ExportFonts(bool exportAsBase64) { Document doc = new Document(MyDir + "Document.doc"); HtmlSaveOptions saveOptions = new HtmlSaveOptions { ExportFontResources = true, ExportFontsAsBase64 = exportAsBase64 }; switch (exportAsBase64) { case false: doc.Save(MyDir + @"\Artifacts\DocumentExportFonts.html", saveOptions); // Verify that the font has been added to the folder Assert.IsNotEmpty(Directory.GetFiles(MyDir + @"Artifacts\", "DocumentExportFonts.times.ttf", SearchOption.AllDirectories)); break; case true: doc.Save(MyDir + @"\Artifacts\DocumentExportFonts.html", saveOptions); // Verify that the font is not added to the folder Assert.IsEmpty(Directory.GetFiles(MyDir + @"Artifacts\", "DocumentExportFonts.times.ttf", SearchOption.AllDirectories)); break; } }
public void ExportOfficeMath(SaveFormat saveFormat, HtmlOfficeMathOutputMode outputMode) { Document doc = new Document(MyDir + "OfficeMath.docx"); HtmlSaveOptions saveOptions = new HtmlSaveOptions { OfficeMathOutputMode = outputMode }; Save(doc, @"\Artifacts\HtmlSaveOptions.ExportToHtmlUsingImage." + saveFormat.ToString().ToLower(), saveFormat, saveOptions); switch (saveFormat) { case SaveFormat.Html: DocumentHelper.FindTextInFile( MyDir + @"\Artifacts\HtmlSaveOptions.ExportToHtmlUsingImage." + saveFormat.ToString().ToLower(), "<img src=\"HtmlSaveOptions.ExportToHtmlUsingImage.001.png\" width=\"49\" height=\"19\" alt=\"\" style=\"-aw-left-pos:0pt; -aw-rel-hpos:column; -aw-rel-vpos:paragraph; -aw-top-pos:0pt; -aw-wrap-type:inline\" />"); return; case SaveFormat.Mhtml: DocumentHelper.FindTextInFile( MyDir + @"\Artifacts\HtmlSaveOptions.ExportToHtmlUsingImage." + saveFormat.ToString().ToLower(), "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mi>A</mi><mo>=</mo><mi>Ï€</mi><msup><mrow><mi>r</mi></mrow><mrow><mn>2</mn></mrow></msup></math>"); return; case SaveFormat.Epub: DocumentHelper.FindTextInFile( MyDir + @"\Artifacts\HtmlSaveOptions.ExportToHtmlUsingImage." + saveFormat.ToString().ToLower(), "<span style=\"font-family:\'Cambria Math\'\">A=Ï€</span><span style=\"font-family:\'Cambria Math\'\">r</span><span style=\"font-family:\'Cambria Math\'\">2</span>"); return; } }
public static void Run() { try { // ExStart:PrefixToImportDirectives // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion_PDFToHTMLFormat(); string linceseFile = ""; // E.g @"F:\_Sources\Aspose.Total.lic" (new Aspose.Pdf.License()).SetLicense(linceseFile); Document pdfDocument = new Document(dataDir + "input.pdf"); string outHtmlFile = dataDir + "PrefixToImportDirectives_out.html"; _folderForReferencedResources_36435 = dataDir; // Create HtmlSaveOption with tested feature HtmlSaveOptions saveOptions = new HtmlSaveOptions(); saveOptions.CustomStrategyOfCssUrlCreation = new HtmlSaveOptions.CssUrlMakingStrategy(Strategy_10_CSS_ReturnResultPathInPredefinedTestFolder); saveOptions.CustomCssSavingStrategy = new HtmlSaveOptions.CssSavingStrategy(Strategy_10_CSS_WriteCssToResourceFolder); //---------------------------------------------------------------------------- // Run converter //---------------------------------------------------------------------------- pdfDocument.Save(outHtmlFile, saveOptions); // ExEnd:PrefixToImportDirectives } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public void ConvertNodeToHtmlWithDefaultOptions() { //ExStart //ExFor:Node.ToString(SaveFormat) //ExFor:Node.ToString(SaveOptions) //ExSummary:Exports the content of a node to String in HTML format. Document doc = new Document(MyDir + "Document.docx"); Node node = doc.LastSection.Body.LastParagraph; // When we call the ToString method using the html SaveFormat overload, // it converts the node's contents to their raw html representation. Assert.AreEqual("<p style=\"margin-top:0pt; margin-bottom:8pt; line-height:108%; font-size:12pt\">" + "<span style=\"font-family:'Times New Roman'\">Hello World!</span>" + "</p>", node.ToString(SaveFormat.Html)); // We can also modify the result of this conversion using a SaveOptions object. HtmlSaveOptions saveOptions = new HtmlSaveOptions(); saveOptions.ExportRelativeFontSize = true; Assert.AreEqual("<p style=\"margin-top:0pt; margin-bottom:8pt; line-height:108%\">" + "<span style=\"font-family:'Times New Roman'\">Hello World!</span>" + "</p>", node.ToString(saveOptions)); //ExEnd }
public void MetafileFormat() { //ExStart //ExFor:HtmlSaveOptions.MetafileFormat //ExSummary:Shows how to set a meta file in a different format. // Create a document from an html string string html = @"<html> <svg xmlns='http://www.w3.org/2000/svg' width='500' height='40' viewBox='0 0 500 40'> <text x='0' y='35' font-family='Verdana' font-size='35'>Hello world!</text> </svg> </html>"; Document doc = new Document(new MemoryStream(Encoding.UTF8.GetBytes(html))); // This document contains a <svg> element in the form of text, // which by default will be saved as a linked external .png when we save the document as html // We can save with a HtmlSaveOptions object with this flag set to preserve the <svg> tag HtmlSaveOptions options = new HtmlSaveOptions(); options.MetafileFormat = HtmlMetafileFormat.Svg; doc.Save(ArtifactsDir + "HtmlSaveOptions.MetafileFormat.html", options); //ExEnd }
public void ExportTocPageNumbers() { //ExStart //ExFor:HtmlSaveOptions.ExportTocPageNumbers //ExSummary:Shows how to display page numbers when saving a document with a table of contents to .html. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert a table of contents FieldToc fieldToc = (FieldToc)builder.InsertField(FieldType.FieldTOC, true); // Populate the document with paragraphs of a "Heading" style that the table of contents will pick up builder.ParagraphFormat.Style = builder.Document.Styles["Heading 1"]; builder.InsertBreak(BreakType.PageBreak); builder.Writeln("Entry 1"); builder.Writeln("Entry 2"); builder.InsertBreak(BreakType.PageBreak); builder.Writeln("Entry 3"); builder.InsertBreak(BreakType.PageBreak); builder.Writeln("Entry 4"); // Our headings span several pages, and those page numbers will be displayed by the TOC at the top of the document fieldToc.UpdatePageNumbers(); doc.UpdateFields(); // These page numbers are normally omitted since .html has no pagination, but we can still have them displayed // if we save with a HtmlSaveOptions object with the ExportTocPageNumbers set to true HtmlSaveOptions options = new HtmlSaveOptions(); options.ExportTocPageNumbers = true; doc.Save(ArtifactsDir + "HtmlSaveOptions.ExportTocPageNumbers.html", options); //ExEnd }
public void ExportPageSetup() { //ExStart //ExFor:HtmlSaveOptions.ExportPageSetup //ExSummary:Shows how to preserve section structure/page setup information when saving to html. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Use a DocumentBuilder to insert two sections with text builder.Writeln("Section 1"); builder.InsertBreak(BreakType.SectionBreakNewPage); builder.Writeln("Section 2"); // Change dimensions and paper size of first section PageSetup pageSetup = doc.Sections[0].PageSetup; pageSetup.TopMargin = 36.0; pageSetup.BottomMargin = 36.0; pageSetup.PaperSize = PaperSize.A5; // Section structure and pagination are normally lost when when converting to .html // We can create an HtmlSaveOptions object with the ExportPageSetup flag set to true // to preserve the section structure in <div> tags and page dimensions in the output document's CSS HtmlSaveOptions options = new HtmlSaveOptions { ExportPageSetup = true, PrettyFormat = true }; doc.Save(ArtifactsDir + "HtmlSaveOptions.ExportPageSetup.html", options); //ExEnd }
public void RelativeFontSize() { //ExStart //ExFor:HtmlSaveOptions.ExportRelativeFontSize //ExSummary:Shows how to use relative font sizes when saving to .html. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Use a builder to write some text in various sizes builder.Writeln("Default font size, "); builder.Font.Size = 24.0; builder.Writeln("2x default font size,"); builder.Font.Size = 96; builder.Write("8x default font size"); // We can save font sizes as ratios of the default size, which will be 12 in this case // If we use an input .html, this size can be set with the AbsSize {font-size:12pt} tag // The ExportRelativeFontSize will enable this feature HtmlSaveOptions options = new HtmlSaveOptions { ExportRelativeFontSize = true, PrettyFormat = true }; doc.Save(ArtifactsDir + "HtmlSaveOptions.RelativeFontSize.html", options); //ExEnd }
public void List() { //ExStart //ExFor:HtmlSaveOptions.ExportListLabels //ExSummary:Shows how to export an indented list to .html as plain text. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Use the builder to insert a list Aspose.Words.Lists.List list = doc.Lists.Add(ListTemplate.NumberDefault); builder.ListFormat.List = list; builder.Writeln("List item 1."); builder.ListFormat.ListIndent(); builder.Writeln("List item 2."); builder.ListFormat.ListIndent(); builder.Write("List item 3."); // When we save this to .html, normally our list will be represented by <li> tags // We can set this flag to have lists as plain text instead HtmlSaveOptions options = new HtmlSaveOptions { ExportListLabels = ExportListLabels.AsInlineText, PrettyFormat = true }; doc.Save(ArtifactsDir + "HtmlSaveOptions.List.html", options); //ExEnd }
public void ExportPageMargins() { //ExStart //ExFor:HtmlSaveOptions.ExportPageMargins //ExSummary:Shows how to show out-of-bounds objects in output .html documents. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Use a builder to insert a shape with no wrapping Shape shape = builder.InsertShape(ShapeType.Cube, 200, 200); shape.RelativeHorizontalPosition = RelativeHorizontalPosition.Page; shape.RelativeVerticalPosition = RelativeVerticalPosition.Page; shape.WrapType = WrapType.None; // Negative values for shape position may cause the shape to go out of page bounds // If we export this to .html, the shape will be truncated shape.Left = -150; // We can avoid that and have the entire shape be visible by setting this flag HtmlSaveOptions options = new HtmlSaveOptions(); options.ExportPageMargins = true; doc.Save(ArtifactsDir + "HtmlSaveOptions.ExportPageMargins.html", options); //ExEnd }
public static void Run() { //Output directory string outputDir = RunExamples.Get_OutputDirectory(); //Create workbook object Workbook wb = new Workbook(); //Access first worksheet Worksheet ws = wb.Worksheets[0]; //Access cell B5 and put value inside it Cell cell = ws.Cells["B5"]; cell.PutValue("This is some text."); //Set the style of the cell - font color is Red Style st = cell.GetStyle(); st.Font.Color = Color.Red; cell.SetStyle(st); //Specify html save options - specify table css id HtmlSaveOptions opts = new HtmlSaveOptions(); opts.TableCssId = "MyTest_TableCssId"; //Save the workbook in html wb.Save(outputDir + "outputTableCssId.html", opts); Console.WriteLine("PrefixTableElementsStylesWithHtmlSaveOptions_TableCssIdProperty executed successfully."); }
public void ExportLanguageInformation() { //ExStart //ExFor:HtmlSaveOptions.ExportLanguageInformation //ExSummary:Shows how to preserve language information when saving to .html. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Use the builder to write text in more than one language builder.Font.LocaleId = 2057; // en-GB builder.Writeln("Hello world!"); builder.Font.LocaleId = 1049; // ru-RU builder.Write("Привет, мир!"); // Normally, when saving a document with more than one proofing language to .html, // only the text content is preserved with no traces of any other languages // Saving with a HtmlSaveOptions object with this flag set will add "lang" attributes to spans // in places where other proofing languages were used HtmlSaveOptions options = new HtmlSaveOptions { ExportLanguageInformation = true, PrettyFormat = true }; doc.Save(ArtifactsDir + "HtmlSaveOptions.ExportLanguageInformation.html", options); //ExEnd }
public void FolderAlias() { //ExStart //ExFor:HtmlSaveOptions.ExportOriginalUrlForLinkedImages //ExFor:HtmlSaveOptions.FontsFolder //ExFor:HtmlSaveOptions.FontsFolderAlias //ExFor:HtmlSaveOptions.ImageResolution //ExFor:HtmlSaveOptions.ImagesFolderAlias //ExFor:HtmlSaveOptions.ResourceFolder //ExFor:HtmlSaveOptions.ResourceFolderAlias //ExSummary:Shows how to set folders and folder aliases for externally saved resources when saving to html. Document doc = new Document(MyDir + "Rendering.doc"); HtmlSaveOptions options = new HtmlSaveOptions { CssStyleSheetType = CssStyleSheetType.External, ExportFontResources = true, ImageResolution = 72, FontResourcesSubsettingSizeThreshold = 0, FontsFolder = ArtifactsDir + "Fonts", ImagesFolder = ArtifactsDir + "Images", ResourceFolder = ArtifactsDir + "Resources", FontsFolderAlias = "http://example.com/fonts", ImagesFolderAlias = "http://example.com/images", ResourceFolderAlias = "http://example.com/resources", ExportOriginalUrlForLinkedImages = true }; doc.Save(ArtifactsDir + "HtmlSaveOptions.FolderAlias.html", options); //ExEnd }
public void EpubHeadings() { //ExStart //ExFor:HtmlSaveOptions.EpubNavigationMapLevel //ExSummary:Shows the relationship between heading levels and the Epub navigation panel. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert headings of levels 1 - 3 builder.ParagraphFormat.Style = builder.Document.Styles["Heading 1"]; builder.Writeln("Heading #1"); builder.ParagraphFormat.Style = builder.Document.Styles["Heading 2"]; builder.Writeln("Heading #2"); builder.ParagraphFormat.Style = builder.Document.Styles["Heading 3"]; builder.Writeln("Heading #3"); builder.ParagraphFormat.Style = builder.Document.Styles["Heading 1"]; builder.Writeln("Heading #4"); builder.ParagraphFormat.Style = builder.Document.Styles["Heading 2"]; builder.Writeln("Heading #5"); builder.ParagraphFormat.Style = builder.Document.Styles["Heading 3"]; builder.Writeln("Heading #6"); // Epub readers normally treat paragraphs with "Heading" styles as anchors for a table of contents-style navigation pane // We set a maximum heading level above which headings won't be registered by the reader as navigation points with // a HtmlSaveOptions object and its EpubNavigationLevel attribute // Our document has headings of levels 1 to 3, // but our output epub will only place level 1 and 2 headings in the table of contents HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Epub); options.EpubNavigationMapLevel = 2; doc.Save(ArtifactsDir + "HtmlSaveOptions.EpubHeadings.epub", options); //ExEnd }
public void HeadingLevels() { //ExStart //ExFor:HtmlSaveOptions.DocumentSplitHeadingLevel //ExSummary:Shows how to split a document into several html documents by heading levels. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert headings of levels 1 - 3 builder.ParagraphFormat.Style = builder.Document.Styles["Heading 1"]; builder.Writeln("Heading #1"); builder.ParagraphFormat.Style = builder.Document.Styles["Heading 2"]; builder.Writeln("Heading #2"); builder.ParagraphFormat.Style = builder.Document.Styles["Heading 3"]; builder.Writeln("Heading #3"); builder.ParagraphFormat.Style = builder.Document.Styles["Heading 1"]; builder.Writeln("Heading #4"); builder.ParagraphFormat.Style = builder.Document.Styles["Heading 2"]; builder.Writeln("Heading #5"); builder.ParagraphFormat.Style = builder.Document.Styles["Heading 3"]; builder.Writeln("Heading #6"); // Create a HtmlSaveOptions object and set the split criteria to "HeadingParagraph", meaning that the document // will be split into parts at the beginning of every paragraph of a "Heading" style, and each part will be saved as a separate document // Also, we will set the DocumentSplitHeadingLevel to 2, which will split the document only at headings that have levels from 1 to 2 HtmlSaveOptions options = new HtmlSaveOptions { DocumentSplitCriteria = DocumentSplitCriteria.HeadingParagraph, DocumentSplitHeadingLevel = 2 }; doc.Save(ArtifactsDir + "HtmlSaveOptions.HeadingLevels.html", options); //ExEnd }
public void NegativeIndent() { //ExStart //ExFor:HtmlSaveOptions.AllowNegativeIndent //ExFor:HtmlSaveOptions.TableWidthOutputMode //ExSummary:Shows how to preserve negative indents in the output .html. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Insert a table and give it a negative value for its indent, effectively pushing it out of the left page boundary Table table = builder.StartTable(); builder.InsertCell(); builder.Write("Cell 1"); builder.InsertCell(); builder.Write("Cell 2"); builder.EndTable(); table.LeftIndent = -36; table.PreferredWidth = PreferredWidth.FromPoints(144); // When saving to .html, this indent will only be preserved if we set this flag HtmlSaveOptions options = new HtmlSaveOptions(SaveFormat.Html); options.AllowNegativeIndent = true; options.TableWidthOutputMode = HtmlElementSizeOutputMode.RelativeOnly; // The first cell with "Cell 1" will not be visible in the output doc.Save(ArtifactsDir + "HtmlSaveOptions.AllowNegativeIndent.html", options); //ExEnd }
public void ConvertNodeToHtmlWithSaveOptions() { //ExStart //ExFor:Node.ToString(SaveOptions) //ExSummary:Exports the content of a node to String in HTML format using custom specified options. Document doc = new Document(MyDir + "Document.doc"); // Extract the last paragraph in the document to convert to HTML. Node node = doc.LastSection.Body.LastParagraph; // Create an instance of HtmlSaveOptions and set a few options. HtmlSaveOptions saveOptions = new HtmlSaveOptions { ExportHeadersFootersMode = ExportHeadersFootersMode.PerSection, ExportRelativeFontSize = true }; // Convert the document to HTML and return as a String. Pass the instance of HtmlSaveOptions to // to use the specified options during the conversion. String nodeAsHtml = node.ToString(saveOptions); //ExEnd Assert.AreEqual( "<p style=\"margin-top:0pt; margin-bottom:0pt\"><span style=\"font-family:'Times New Roman'\">Hello World!</span></p>", nodeAsHtml); }
static void Main(string[] args) { string MyDir = @"Files\"; // Open an existing document from disk. Document doc = new Document(MyDir + "Converting Document.docx"); // Create a new instance of HtmlSaveOptions. This object allows us to set options that control // how the output document is saved. HtmlSaveOptions saveOptions = new HtmlSaveOptions(); // Specify the desired encoding. saveOptions.Encoding = System.Text.Encoding.UTF8; // Specify at what elements to split the internal HTML at. This creates a new HTML within the EPUB // which allows you to limit the size of each HTML part. This is useful for readers which cannot read // HTML files greater than a certain size e.g 300kb. saveOptions.DocumentSplitCriteria = DocumentSplitCriteria.HeadingParagraph; // Specify that we want to export document properties. saveOptions.ExportDocumentProperties = true; // Specify that we want to save in EPUB format. saveOptions.SaveFormat = SaveFormat.Epub; // Export the document as an EPUB file. doc.Save(MyDir + "Document.EpubConversion Out.epub", saveOptions); }
public void FontSubsetting() { //ExStart //ExFor:HtmlSaveOptions.FontResourcesSubsettingSizeThreshold //ExSummary:Shows how to work with font subsetting. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); // Use a DocumentBuilder to insert text with several fonts builder.Font.Name = "Arial"; builder.Writeln("Hello world!"); builder.Font.Name = "Times New Roman"; builder.Writeln("Hello world!"); builder.Font.Name = "Courier New"; builder.Writeln("Hello world!"); // When saving to .html, font subsetting fully applies by default, meaning that when we export fonts with our file, // the symbols not used by our document are not represented by the exported fonts, which cuts down file size dramatically // Font files of a file size larger than FontResourcesSubsettingSizeThreshold get subsetted, so a value of 0 will apply default full subsetting // Setting the value to something large will fully suppress subsetting, saving some very large font files that cover every glyph HtmlSaveOptions options = new HtmlSaveOptions { ExportFontResources = true, FontResourcesSubsettingSizeThreshold = int.MaxValue }; doc.Save(ArtifactsDir + "HtmlSaveOptions.FontSubsetting.html", options); //ExEnd }
public void ExportTextBoxAsSvg(SaveFormat saveFormat, bool isTextBoxAsSvg) { string[] dirFiles; Document doc = new Document(MyDir + "HtmlSaveOptions.ExportTextBoxAsSvg.docx"); HtmlSaveOptions saveOptions = new HtmlSaveOptions(saveFormat); saveOptions.ExportTextBoxAsSvg = isTextBoxAsSvg; doc.Save(ArtifactsDir + "HtmlSaveOptions.ExportTextBoxAsSvg" + FileFormatUtil.SaveFormatToExtension(saveFormat), saveOptions); switch (saveFormat) { case SaveFormat.Html: dirFiles = Directory.GetFiles(ArtifactsDir, "HtmlSaveOptions.ExportTextBoxAsSvg.001.png", SearchOption.AllDirectories); Assert.That(dirFiles, Is.Empty); return; case SaveFormat.Epub: dirFiles = Directory.GetFiles(ArtifactsDir, "HtmlSaveOptions.ExportTextBoxAsSvg.001.png", SearchOption.AllDirectories); Assert.That(dirFiles, Is.Empty); return; case SaveFormat.Mhtml: dirFiles = Directory.GetFiles(ArtifactsDir, "HtmlSaveOptions.ExportTextBoxAsSvg.001.png", SearchOption.AllDirectories); Assert.That(dirFiles, Is.Empty); return; } }
static void Main(string[] args) { string FilePath = @"..\..\..\Sample Files\"; string FileName = FilePath + "Converting Document.docx"; // Open an existing document from disk. Document doc = new Document(FileName); // Create a new instance of HtmlSaveOptions. This object allows us to set options that control // how the output document is saved. HtmlSaveOptions saveOptions = new HtmlSaveOptions(); // Specify the desired encoding. saveOptions.Encoding = System.Text.Encoding.UTF8; // Specify at what elements to split the internal HTML at. This creates a new HTML within the EPUB // which allows you to limit the size of each HTML part. This is useful for readers which cannot read // HTML files greater than a certain size e.g 300kb. saveOptions.DocumentSplitCriteria = DocumentSplitCriteria.HeadingParagraph; // Specify that we want to export document properties. saveOptions.ExportDocumentProperties = true; // Specify that we want to save in EPUB format. saveOptions.SaveFormat = SaveFormat.Epub; // Export the document as an EPUB file. doc.Save(FilePath + "Document.EpubConversion Out.epub", saveOptions); }
private static void WOFFFormat() { // Create HtmlSaveOption with tested feature HtmlSaveOptions saveOptions = new HtmlSaveOptions(); // ExStart:WOFFFormat saveOptions.FontSavingMode = HtmlSaveOptions.FontSavingModes.AlwaysSaveAsWOFF; // ExEnd:WOFFFormat }
// ExStart:SplitCSSToPagesHelpers private static void Strategy_4_CSS_MULTIPAGE_SAVING_RIGHT_WAY(HtmlSaveOptions.CssSavingInfo partSavingInfo) { string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion_PDFToHTMLFormat(); string outPath = dataDir + "style_xyz_page" + partSavingInfo.CssNumber.ToString() + ".css"; System.IO.BinaryReader reader = new BinaryReader(partSavingInfo.ContentStream); System.IO.File.WriteAllBytes(outPath, reader.ReadBytes((int)partSavingInfo.ContentStream.Length)); }
// ExStart:SavingToStream private static void SavingToStream(HtmlSaveOptions.HtmlPageMarkupSavingInfo htmlSavingInfo) { byte[] resultHtmlAsBytes = new byte[htmlSavingInfo.ContentStream.Length]; htmlSavingInfo.ContentStream.Read(resultHtmlAsBytes, 0, resultHtmlAsBytes.Length); // Here You can use any writable stream, file stream is taken just as example string fileName = "stream_out.html"; Stream outStream = File.OpenWrite(fileName); outStream.Write(resultHtmlAsBytes, 0, resultHtmlAsBytes.Length); }
private static void CustomSavingOfCss(HtmlSaveOptions.CssSavingInfo resourceInfo) { System.IO.BinaryReader reader = new BinaryReader(resourceInfo.ContentStream); byte[] cssAsBytes = reader.ReadBytes((int)resourceInfo.ContentStream.Length); Console.WriteLine("Css page processed with handler. Length of css in bytes is " + cssAsBytes.Length.ToString()); // Here You can put code that will save page's HTML to some storage, f.e database MemoryStream targetStream = new MemoryStream(); targetStream.Write(cssAsBytes, 0, cssAsBytes.Length); }
private static void Strategy_11_CSS_WriteCssToPredefinedFolder(HtmlSaveOptions.CssSavingInfo resourceInfo) { if (!Directory.Exists(_folderForReferencedResources_34748)) { Directory.CreateDirectory(_folderForReferencedResources_34748); } string path = _folderForReferencedResources_34748 + Path.GetFileName(resourceInfo.SupposedURL); System.IO.BinaryReader reader = new BinaryReader(resourceInfo.ContentStream); System.IO.File.WriteAllBytes(path, reader.ReadBytes((int)resourceInfo.ContentStream.Length)); }
public static void Run() { try { // ExStart:SetOutputFileDimensions // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion_PDFToHTMLFormat(); // Select desirable page size float newPageWidth = 400f; float newPageHeight = 400f; // Tune PdfPageEditor class Aspose.Pdf.Facades.PdfPageEditor pdfEditor = new Aspose.Pdf.Facades.PdfPageEditor(); // Bind source PDF file pdfEditor.BindPdf(dataDir + "input.pdf"); // Set the page dimensions pdfEditor.PageSize = new Aspose.Pdf.PageSize(newPageWidth, newPageHeight); // Set vertical alignment for page as center aligned pdfEditor.VerticalAlignmentType = Aspose.Pdf.VerticalAlignment.Center; // Set Horizontal alignment for page as center aligned pdfEditor.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Center; // This scales page content to fit width, // Comment it out or set Zoom to 1.0F if You don't want to scale // Content and only want to change page's size (i.e. crop it) float zoom = Math.Min((float)newPageWidth / (float)pdfEditor.Document.Pages[1].Rect.Width, (float)newPageHeight / (float)pdfEditor.Document.Pages[1].Rect.Height); pdfEditor.Zoom = zoom;// (float)595; // Create stream object to hold file with updated dimensions MemoryStream output = new MemoryStream(); // Save file to stream object pdfEditor.Save(output); // Then reload scaled document and save it to HTML Document exportDoc = new Document(output); HtmlSaveOptions htmlOptions = new HtmlSaveOptions(); // This code shows page boreder in result - sometimes it comes in handy to see borders SaveOptions.BorderPartStyle borderStyle = new SaveOptions.BorderPartStyle(); borderStyle.LineType = SaveOptions.HtmlBorderLineType.Dotted; borderStyle.Color = System.Drawing.Color.Gray; htmlOptions.PageBorderIfAny = new SaveOptions.BorderInfo(borderStyle); // Conversion to HTML itself exportDoc.Save(dataDir + "SetOutputFileDimensions_out.html", htmlOptions); // Close the stream object output.Close(); // ExEnd:SetOutputFileDimensions } catch (Exception ex) { Console.WriteLine(ex.Message); } }
// ExStart:SaveHTMLImageCSSHelper private static void StrategyOfSavingHtml(HtmlSaveOptions.HtmlPageMarkupSavingInfo htmlSavingInfo) { // Get target file name and write content to it System.IO.BinaryReader reader = new BinaryReader(htmlSavingInfo.ContentStream); byte[] htmlAsByte = reader.ReadBytes((int)htmlSavingInfo.ContentStream.Length); Console.WriteLine("Html page processed with handler. Length of page's text in bytes is " + htmlAsByte.Length.ToString()); // Here You can put code that will save page's HTML to some storage, f.e database MemoryStream targetStream = new MemoryStream(); targetStream.Write(htmlAsByte, 0, htmlAsByte.Length); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); string inputPath = dataDir + "Sample1.xlsx"; string outputPath = dataDir + "Output.html"; Workbook workbook = new Workbook(dataDir + "Sample1.xlsx"); HtmlSaveOptions opts = new HtmlSaveOptions(); opts.LinkTargetType = HtmlLinkTargetType.Self; workbook.Save(outputPath, opts); Console.WriteLine("File saved: {0}", outputPath); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Open the required workbook to convert Workbook w = new Workbook(dataDir + "Sample1.xlsx"); // Disable exporting frame scripts and document properties HtmlSaveOptions options = new HtmlSaveOptions(); options.ExportFrameScriptsAndProperties = false; // Save workbook as HTML w.Save(dataDir + "output.out.html", options); }
public static void ThreeSetFonts() { // ExStart:ThreeSetFonts // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion_PDFToHTMLFormat(); Document doc = new Document(dataDir + "input.pdf"); HtmlSaveOptions htmlOptions = new HtmlSaveOptions(); htmlOptions.FixedLayout = true; htmlOptions.RasterImagesSavingMode = HtmlSaveOptions.RasterImagesSavingModes.AsExternalPngFilesReferencedViaSvg; htmlOptions.FontSavingMode = HtmlSaveOptions.FontSavingModes.SaveInAllFormats; doc.Save(dataDir + "ThreeSetFonts_out.html", htmlOptions); // ExEnd:ThreeSetFonts }
public static void Main() { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //Instantiate the Workbook //Load an Excel file Workbook workbook = new Workbook(dataDir+ "sample.xlsx"); //Create HtmlSaveOptions object HtmlSaveOptions options = new HtmlSaveOptions(); //Set the Presenation preference option options.PresentationPreference = true; //Save the Excel file to HTML with specified option workbook.Save(dataDir+ "outPresentationlayout1.html", options); }
public static void Main() { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Instantiate the Workbook //Load an Excel file Workbook workbook = new Workbook(dataDir+ "sample.xlsx"); //Create HtmlSaveOptions object HtmlSaveOptions options = new HtmlSaveOptions(); //Set the Presenation preference option options.PresentationPreference = true; //Save the Excel file to HTML with specified option workbook.Save(dataDir+ "outPresentationlayout1.out.html", options); }
public static void Run() { // ExStart:PreventExportingHiddenContentWhileSavingAsHTML // The path to the documents directory. string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); // Create workbook object Workbook workbook = new Workbook(dataDir + "WorkbookWithHiddenContent.xlsx"); // Do not export hidden worksheet contents HtmlSaveOptions options = new HtmlSaveOptions(); options.ExportHiddenWorksheet = false; // Save the workbook workbook.Save(dataDir + "HtmlWithoutHiddenContent_out.html", options); // ExEnd:PreventExportingHiddenContentWhileSavingAsHTML }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Path.GetFullPath("../../../Data/"); //Specify the file path string filePath = dataDir + "Book1.xlsx"; //Specify the HTML Saving Options HtmlSaveOptions sv = new HtmlSaveOptions(SaveFormat.MHtml); //Instantiate a workbook and open the template XLSX file Workbook wb = new Workbook(filePath); //Save the MHT file wb.Save(filePath + ".out.mht", sv); }
public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Specify the file path string filePath = dataDir + "Book1.xlsx"; //Specify the HTML Saving Options HtmlSaveOptions sv = new HtmlSaveOptions(SaveFormat.MHtml); //Instantiate a workbook and open the template XLSX file Workbook wb = new Workbook(filePath); //Save the MHT file wb.Save(filePath + ".out.mht", sv); }