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.
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 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 de origen a HTML. La enumeración SaveFormat
contiene el valor Html que te permite guardar el archivo de origen en HTML. El siguiente fragmento de código muestra el proceso de conversión de un archivo PDF en HTML.
// 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. Usa la clase HtmlSaveOption
propiedad SpecialFolderForSvgImages
para especificar un directorio especial para imágenes SVG. Esta propiedad obtiene o establece la ruta al directorio al 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 en 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 a 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 y salida de CSS, creación y salida de imágenes), 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 de origen/entrada contenga textos transparentes sombreados por imágenes de 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 código muestra un ejemplo de guardar el archivo recibido en un stream. Se puede usar cualquier tipo de stream para guardar. Este fragmento de código también describe cómo funcionan las estrategias de guardado personalizadas.
// Para ejemplos completos y archivos de datos, visita https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static string _folderForReferencedResources;
private static void ConvertPDFtoHTMLWithStream()
{
// La ruta al directorio de documentos
var dataDir = RunExamples.GetDataDir_AsposePdf();
// Abrir documento PDF
using (var doc = new Aspose.Pdf.Document(dataDir + "PDFToHTML.pdf"))
{
var streamFilePath = dataDir + "saveToStream.html";
_folderForReferencedResources = dataDir + @"/saveFolder/";
// Limpiar archivos existentes
if (Directory.Exists(_folderForReferencedResources))
{
Directory.Delete(_folderForReferencedResources, true);
}
// Limpiar archivos existentes
if (File.Exists(streamFilePath))
{
File.Delete(streamFilePath);
}
var saveOptions = new Aspose.Pdf.HtmlSaveOptions();
// Configurando estrategias personalizadas para la conversión
saveOptions.CustomResourceSavingStrategy = new Aspose.Pdf.HtmlSaveOptions.ResourceSavingStrategy(StrategyCustomSaveResources);
saveOptions.CustomCssSavingStrategy = new Aspose.Pdf.HtmlSaveOptions.CssSavingStrategy(StrategyCssSaving);
saveOptions.CustomStrategyOfCssUrlCreation = new Aspose.Pdf.HtmlSaveOptions.CssUrlMakingStrategy(StrategyCssNaming);
using (Stream saveStream = File.OpenWrite(streamFilePath))
{
// Guardar documento en el stream
doc.Save(saveStream, saveOptions);
}
}
}
private static void StrategyCssSaving(Aspose.Pdf.HtmlSaveOptions.CssSavingInfo resourceInfo)
{
// Limpiar archivos existentes
if (!System.IO.Directory.Exists(_folderForReferencedResources))
{
System.IO.Directory.CreateDirectory(_folderForReferencedResources);
}
// Crear una ruta para un css
string path = _folderForReferencedResources + Path.GetFileName(resourceInfo.SupposedURL);
var reader = new System.IO.BinaryReader(resourceInfo.ContentStream);
// Grabar un css en la ruta creada
System.IO.File.WriteAllBytes(path, reader.ReadBytes((int)resourceInfo.ContentStream.Length));
}
private static string StrategyCssNaming(Aspose.Pdf.HtmlSaveOptions.CssUrlRequestInfo requestInfo)
{
return _folderForReferencedResources + "css_style{0}.css";
}
private static string StrategyCustomSaveResources(Aspose.Pdf.SaveOptions.ResourceSavingInfo resourceSavingInfo)
{
// Limpiar archivos existentes
if (!System.IO.Directory.Exists(_folderForReferencedResources))
{
System.IO.Directory.CreateDirectory(_folderForReferencedResources);
}
// Crear una ruta para un recurso
var resourcePath = _folderForReferencedResources + System.IO.Path.GetFileName(resourceSavingInfo.SupposedFileName);
var binaryReader = new System.IO.BinaryReader(resourceSavingInfo.ContentStream);
// Grabar un recurso en la ruta creada
System.IO.File.WriteAllBytes(resourcePath, binaryReader.ReadBytes((int)resourceSavingInfo.ContentStream.Length));
var urlInHtml = _folderForReferencedResources.Replace(@"\", "/") + System.IO.Path.GetFileName(resourceSavingInfo.SupposedFileName);
// Devolver el nombre del recurso para insertar en html
return urlInHtml;
}
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.