Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.
Este artículo explica cómo convertir PDF a HTML usando C#. Cubre estos temas.
Formato: HTML
El siguiente fragmento de código también funciona con la biblioteca Aspose.PDF.Drawing.
Aspose.PDF for .NET proporciona muchas características para convertir varios formatos de archivo en documentos PDF y convertir archivos PDF en varios formatos de salida. Este artículo discute cómo convertir un archivo PDF en HTML. Aspose.PDF for .NET proporciona la capacidad de convertir archivos HTML en formato PDF utilizando el enfoque InLineHtml. Hemos recibido muchas solicitudes para una funcionalidad que convierta un archivo PDF en formato HTML y hemos proporcionado esta característica. Ten en cuenta que esta característica también admite XHTML 1.0.
Aspose.PDF for .NET admite las características para convertir un archivo PDF en HTML. Las principales tareas que puedes realizar con la biblioteca Aspose.PDF están listadas:
Intenta convertir PDF a HTML en línea
Aspose.PDF for .NET te presenta una aplicación gratuita en línea “PDF a HTML”, donde puedes intentar investigar la funcionalidad y la calidad con la que funciona.
Aspose.PDF for .NET proporciona un código de dos líneas para transformar un archivo PDF fuente a HTML. La enumeración SaveFormat
contiene el valor Html que te permite guardar el archivo fuente en HTML. El siguiente fragmento de código muestra el proceso de conversión de un archivo PDF en HTML.
Pasos: Convertir PDF a HTML en C#
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertPDFtoHTML()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf();
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "PDFToHTML.pdf"))
{
// Save the output HTML
document.Save(dataDir + "output_out.html", Aspose.Pdf.SaveFormat.Html);
}
}
Al convertir un archivo PDF grande con varias páginas a formato HTML, la salida aparece como una sola página HTML. Puede terminar siendo muy larga. Para controlar el tamaño de la página, es posible dividir la salida en varias páginas durante la conversión de PDF a HTML. Por favor, intenta usar el siguiente fragmento de código.
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertPDFtoMultiPageHTML()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf();
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "PDFToHTML.pdf"))
{
// Instantiate HTML SaveOptions object
var htmlOptions = new Aspose.Pdf.HtmlSaveOptions
{
// Specify to split the output into multiple pages
SplitIntoPages = true
};
// Save the output HTML
document.Save(dataDir + "MultiPageHTML_out.html", htmlOptions);
}
}
Durante la conversión de PDF a HTML, es posible especificar la carpeta en la que se deben guardar las imágenes SVG. Utiliza la clase HtmlSaveOption
propiedad SpecialFolderForSvgImages
para especificar un directorio especial para imágenes SVG. Esta propiedad obtiene o establece la ruta al directorio en el que se deben guardar las imágenes SVG cuando se encuentran durante la conversión. Si el parámetro está vacío o es nulo, entonces cualquier archivo SVG se guarda junto con otros archivos de imagen.
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void SavePDFtoHTMLWithSVG()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf();
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "PDFToHTML.pdf"))
{
// Instantiate HTML save options object
var newOptions = new Aspose.Pdf.HtmlSaveOptions
{
// Specify the folder where SVG images are saved during PDF to HTML conversion
SpecialFolderForSvgImages = dataDir
};
// Save the output HTML
document.Save(dataDir + "SaveSVGFiles_out.html", newOptions);
}
}
Para comprimir imágenes SVG durante la conversión de PDF a HTML, por favor intenta usar el siguiente código:
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void SavePDFtoCompressedHTMLWithSVG()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf();
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "PDFToHTML.pdf"))
{
// Create HtmlSaveOptions with tested feature
var newOptions = new Aspose.Pdf.HtmlSaveOptions
{
// Compress the SVG images if there are any
CompressSvgGraphicsIfAny = true
};
// Save the output HTML
document.Save(dataDir + "CompressedSVGHTML_out.html", newOptions);
}
}
El formato de salida predeterminado para guardar imágenes es SVG. Durante la conversión, algunas imágenes del PDF se transforman en imágenes vectoriales SVG. Esto podría ser lento. En su lugar, las imágenes podrían transformarse en un archivo de fondo PNG para cada página.
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void PdfToHtmlSaveImagesAsPngBackground()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf_DocumentConversion_PDFToHTMLFormat();
// Create HtmlSaveOption with tested feature
var htmlSaveOptions = new HtmlSaveOptions();
// Option to save images in PNG format as background for each page.
htmlSaveOptions.RasterImagesSavingMode = HtmlSaveOptions.RasterImagesSavingModes.AsEmbeddedPartsOfPngPageBackground;
using (var document = new Aspose.Pdf.Document(dataDir + "input.pdf"))
{
document.Save(dataDir + "imagesAsPngBackground_out.html", htmlSaveOptions);
}
}
También podemos especificar la carpeta a la que se guardarán las imágenes durante la conversión de PDF a HTML:
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void SavePDFtoHTMLWithSeparateImageFolder()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf();
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "PDFToHTML.pdf"))
{
// Create HtmlSaveOptions with tested feature
var newOptions = new Aspose.Pdf.HtmlSaveOptions
{
// Specify the separate folder to save images
SpecialFolderForAllImages = dataDir
};
// Save the output HTML
document.Save(dataDir + "HTMLWithSeparateImageFolder_out.html", newOptions);
}
}
Recientemente, se nos pidió que introdujéramos una característica donde los archivos PDF se convierten en HTML y el usuario puede obtener solo el contenido de la etiqueta <body>
para cada página. Esto produciría un archivo con detalles de CSS, <html>
, <head>
y todas las páginas en otros archivos solo con el contenido de <body>
.
Para cumplir con este requisito, se introdujo una nueva propiedad, HtmlMarkupGenerationMode, en la clase HtmlSaveOptions.
Con el siguiente fragmento de código simple, puedes dividir la salida HTML en páginas. En las páginas de salida, todos los objetos HTML deben ir exactamente donde van ahora (procesamiento de fuentes y salida, creación de CSS y salida, creación de imágenes y salida), excepto que el HTML de salida contendrá contenidos actualmente colocados dentro de las etiquetas (ahora se omitirán las etiquetas “body”). Sin embargo, al usar este enfoque, el enlace al CSS es responsabilidad de tu código, porque cosas como se eliminarán. Para este propósito, puedes leer el CSS a través de File.ReadAllText() y enviarlo a través de AJAX a una página web donde se aplicará mediante jQuery.
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertPDFToHTMLWithBodyContent()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf();
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "PDFToHTML.pdf"))
{
// Initialize HtmlSaveOptions
var options = new Aspose.Pdf.HtmlSaveOptions
{
// Set HtmlMarkupGenerationMode to generate only body content
HtmlMarkupGenerationMode =
Aspose.Pdf.HtmlSaveOptions.HtmlMarkupGenerationModes.WriteOnlyBodyContent,
// Specify to split the output into multiple pages
SplitIntoPages = true
};
// Save the output HTML
document.Save(dataDir + "CreateSubsequentFiles_out.html", options);
}
}
En caso de que el archivo PDF fuente/entrada contenga textos transparentes sombreados por imágenes en primer plano, entonces podría haber problemas de renderizado de texto. Así que para atender tales escenarios, se pueden usar las propiedades SaveShadowedTextsAsTransparentTexts y SaveTransparentTexts.
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertPDFToHTMLWithTransparentTextRendering()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf();
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "PDFToHTML.pdf"))
{
// Initialize HtmlSaveOptions
var htmlOptions = new Aspose.Pdf.HtmlSaveOptions
{
// Enable transparent text rendering
SaveShadowedTextsAsTransparentTexts = true,
SaveTransparentTexts = true
};
// Save the output HTML
document.Save(dataDir + "TransparentTextRendering_out.html", htmlOptions);
}
}
Podemos renderizar capas de documentos PDF en un elemento de tipo capa separado durante la conversión de PDF a HTML:
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertPDFToHTMLWithLayersRendering()
{
// The path to the documents directory
var dataDir = RunExamples.GetDataDir_AsposePdf();
// Open PDF document
using (var document = new Aspose.Pdf.Document(dataDir + "PDFToHTML.pdf"))
{
// Instantiate HTML SaveOptions object
var htmlOptions = new Aspose.Pdf.HtmlSaveOptions
{
// Enable rendering of PDF document layers separately in the output HTML
ConvertMarkedContentToLayers = true
};
// Save the output HTML
document.Save(dataDir + "LayersRendering_out.html", htmlOptions);
}
}
Este artículo también cubre estos temas. Los códigos son los mismos que los anteriores.
Formato: HTML
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.