Thursday, 06 July 2023 03:37

C#/VB.NET : convertir Word en PDF

PDF présente de nombreux avantages par rapport aux documents Word, par exemple, il a une mise en page fixe qui garantit que la mise en forme et le contenu du document restent les mêmes lorsqu'ils sont visualisés sur une variété d'appareils ainsi que de systèmes d'exploitation. Compte tenu de cela, il est plus recommandé de convertir les documents Word en PDF lors du partage et du transfert. Dans cet article, vous apprendrez comment convertir Word en PDF et comment définir les options de conversion en C# et VB.NET à l'aide de Spire.Doc for .NET.

Installer Spire.Doc for .NET

Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.Doc for.NET en tant que références dans votre projet .NET. Les fichiers DLL peuvent être téléchargés à partir de ce lien ou installés via NuGet.

PM> Install-Package Spire.Doc

Convertir Doc ou Docx en PDF en C# et VB.NET

La méthode Document.SaveToFile(string fileName, FileFormat fileFormat) fournie par Spire.Doc pour .NET permet d'enregistrer Word au format PDF, XPS, HTML, RTF, etc. Si vous souhaitez simplement enregistrer vos documents Word au format PDF standard sans paramètres supplémentaires , suivez les étapes ci-dessous.

  • Créez un objet Document.
  • Chargez un exemple de document Word à l'aide de la méthode Document.LoadFromFile().
  • Enregistrez le document au format PDF à l'aide de la méthode Doucment.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace ToPDF
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load a sample Word document
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\Test.docx");
    
                //Save the document to PDF
                document.SaveToFile("ToPDF.pdf", FileFormat.PDF);
            }
        }
    }

C#/VB.NET: Convert Word to PDF

Convertir Word en PDF protégé par mot de passe en C# et VB.NET

Pour convertir Word en PDF protégé par mot de passe, vous pouvez utiliser la méthode Document.SaveToFile(string fileName, ToPdfParameterList paramList). Le paramètre ToPdfParameterList contrôle la façon dont un document Word sera converti en PDF, par exemple, s'il faut chiffrer le document lors de la conversion. Voici les étapes détaillées.

  • Créez un objet Document.
  • Chargez un exemple de document Word à l'aide de la méthode Document.LoadFromFile().
  • Créez un objet ToPdfParameterList, qui est utilisé pour définir les options de conversion.
  • Spécifiez le mot de passe d'ouverture et le mot de passe d'autorisation, puis définissez les deux mots de passe pour le PDF généré à l'aide de la méthode ToPdfParameterList.PdfSecurity.Encrypt().
  • Enregistrez le document Word au format PDF avec un mot de passe à l'aide de la méthode Doucment.SaveToFile(string fileName, ToPdfParameterList paramList).
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace ToPDFWithPassword
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load a sample Word document
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\Test.docx");
    
                //Create a ToPdfParameterList instance
                ToPdfParameterList parameters = new ToPdfParameterList();
    
                //Set open password and permission password for PDF
                string openPsd = "E-iceblue";
                string permissionPsd = "abc123";
                parameters.PdfSecurity.Encrypt(openPsd, permissionPsd, Spire.Pdf.Security.PdfPermissionsFlags.Default, Spire.Pdf.Security.PdfEncryptionKeySize.Key128Bit);
    
                //Save the Word document to PDF with password
                document.SaveToFile("ToPDFWithPassword.pdf", parameters);
            }
        }
    }

C#/VB.NET: Convert Word to PDF

Convertir Word en PDF avec des signets en C# et VB.NET

Les signets peuvent améliorer la lisibilité d'un document. Lors de la génération d'un PDF à partir de Word, vous souhaiterez peut-être conserver les signets existants du document Word ou créer des signets à partir des en-têtes. Voici les étapes pour convertir Word en PDF avec des signets.

  • Créez un objet Document.
  • Chargez un exemple de document Word à l'aide de la méthode Document.LoadFromFile().
  • Créez un objet ToPdfParameterList, qui est utilisé pour définir les options de conversion.
  • Créez des signets PDF à partir de signets Word existants à l'aide de la propriété ToPdfParameterList.CreateWordBookmarks. Ou vous pouvez créer des signets PDF à partir d'en-têtes dans Word à l'aide de la propriété ToPdfParameterList.SetCreateWordBookmarksUsingHeadings.
  • Enregistrez le document au format PDF avec des signets à l'aide de la méthode Doucment.SaveToFile(string fileName, ToPdfParameterList paramList).
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace ToPDFWithBookmarks
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load a sample Word document
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\Test.docx");
    
                //Create a ToPdfParameterList object
                ToPdfParameterList parameters = new ToPdfParameterList();
    
                //Create bookmarks in PDF from existing bookmarks in Word
                parameters.CreateWordBookmarks = true;
    
                //Create bookmarks from Word headings
                //parameters.CreateWordBookmarksUsingHeadings= true;
    
                //Save the document to PDF
                document.SaveToFile("ToPDFWithBookmarks.pdf", parameters);
            }
        }
    }

C#/VB.NET: Convert Word to PDF

Convertir Word en PDF avec des polices intégrées en C# et VB.NET

En incorporant les polices utilisées dans un document Word dans le document PDF, vous vous assurez que le document PDF a le même aspect sur tout appareil sur lequel les polices appropriées ne sont pas installées. Les étapes pour incorporer des polices dans le PDF lors de la conversion sont les suivantes.

  • Créez un objet Document.
  • Chargez un exemple de document Word à l'aide de la méthode Document.LoadFromFile().
  • Créez un objet ToPdfParameterList, qui est utilisé pour définir les options de conversion.
  • Incorporez des polices dans le PDF généré en définissant la propriété ToPdfParameterList.IsEmbeddedAllFonts sur true.
  • Enregistrez le document au format PDF à l'aide de la méthode Doucment.SaveToFile(string fileName, ToPdfParameterList paramList).
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace ToPDFWithFontsEmbedded
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load a sample Word document
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\Test.docx");
    
                //Create a ToPdfParameterList object
                ToPdfParameterList parameters = new ToPdfParameterList();
    
                //Embed all the fonts used in Word in the generated PDF
                parameters.IsEmbeddedAllFonts = true;
    
                //Save the document to PDF
                document.SaveToFile("ToPDFWithFontsEmbedded.pdf", parameters);
            }
        }
    }

C#/VB.NET: Convert Word to PDF

Définir la qualité de l'image lors de la conversion de Word en PDF en C# et VB.NET

Un document contenant un grand nombre d'images de haute qualité sera souvent de grande taille. Lorsque vous convertissez Word en PDF, vous pouvez décider de compresser ou non la qualité de l'image. Voici les étapes détaillées.

  • Créez un objet Document.
  • Chargez un exemple de document Word à l'aide de la méthode Document.LoadFromFile().
  • Définissez la qualité de l'image à l'aide de la propriété Document.JPEGQuality.
  • Enregistrez le document au format PDF à l'aide de la méthode Doucment.SaveToFile().
  • C#
  • VB.NET
using Spire.Doc;
    
    namespace SetImageQuality
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a Document object
                Document document = new Document();
    
                //Load a sample Word document
                document.LoadFromFile(@"C:\Users\Administrator\Desktop\Test.docx");
    
                //Compress image to 40% of the original quality
                document.JPEGQuality = 40;
    
                //Preserve original image quality
                //document.JPEGQuality = 100;
    
                //Save the document to PDF
                document.SaveToFile("SetImageQuantity.pdf", FileFormat.PDF);
            }
        }
    }

Demander une licence temporaire

Si vous souhaitez supprimer le message d'évaluation des documents générés ou vous débarrasser des limitations de fonction, veuillez demander une licence d'essai de 30 jours pour vous-même.

Voir également

Os arquivos PDF têm a vantagem de serem altamente interativos e fáceis de transferir, mas, em alguns casos, também é necessário converter PDF em imagens para incorporação em páginas da Web ou exibição em algumas plataformas que não suportam o formato PDF. Neste artigo, você aprenderá como converter PDF para formatos de imagem JPG, PNG ou BMP em C# e VB.NET usando o Spire.PDF for .NET.

Instalar o Spire.PDF for .NET

Para começar, você precisa adicionar os arquivos DLL incluídos no pacote Spire.PDF for.NET como referências em seu projeto .NET. Os arquivos DLL podem ser baixados deste link ou instalados via NuGet.

PM> Install-Package Spire.PDF 

Converter uma página PDF específica em uma imagem em C# e VB.NET

O Spire.PDF for .NET oferece o método PdfDocument.SaveAsImage() para converter uma página específica em PDF em uma imagem. Em seguida, você pode salvar a imagem como um arquivo JPEG, PNG, BMP, EMF, GIF ou WMF. A seguir estão as etapas detalhadas.

  • Crie uma instância de Documento.
  • Carregue um documento PDF de amostra usando o método PdfDocument.LoadFromFile().
  • Converta uma página específica em uma imagem e defina o Dpi da imagem usando o método PdfDocument.SaveAsImage(int pageIndex, PdfImageType type, int dpiX, int dpiY).
  • Salve a imagem como um arquivo PNG, JPG ou BMP usando o método Image.Save(string filename, ImageFormat format).
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using System.Drawing;
    using System.Drawing.Imaging;
    
    namespace PDFtoImage
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
    
                //Load a sample PDF document
                pdf.LoadFromFile("E:\\Files\\input.pdf");
    
                //Convert the first page to an image and set the image Dpi
                Image image = pdf.SaveAsImage(0, PdfImageType.Bitmap, 500, 500);
    
                //Save the image as a JPG file
                image.Save("ToJPG.jpg", ImageFormat.Jpeg);
    
                //Save the image as a PNG file
                //image.Save("ToPNG.png", ImageFormat.Png);
    
                //Save the image as a BMP file
                //image.Save("ToBMP.bmp", ImageFormat.Bmp);
            }
        }
    }

C#/VB.NET: Convert PDF to Images (JPG, PNG, BMP)

Converta um documento PDF inteiro em várias imagens em C# e VB.NET

Se você deseja converter todo o documento PDF em várias imagens individuais, pode percorrer todas as páginas do PDF e salvá-las como imagens JPG, PNG ou BMP. A seguir estão as etapas detalhadas.

  • Crie uma instância PdfDocument.
  • Carregue um documento PDF de amostra usando o método PdfDocument.LoadFromFile().
  • Percorra todas as páginas do documento e defina o Dpi da imagem ao convertê-las em imagens usando o método PdfDocument.SaveAsImage(int pageIndex, PdfImageType type, int dpiX, int dpiY).
  • Salve as imagens como arquivos PNG usando o método Image.Save().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using System;
    using System.Drawing;
    using System.Drawing.Imaging;
    
    namespace PDFtoImage
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
    
                //Load a sample PDF document
                pdf.LoadFromFile("input.pdf");
    
                //Loop through each page in the PDF
                for (int i = 0; i < pdf.Pages.Count; i++)
                {
                    //Convert all pages to images and set the image Dpi
                    Image image = pdf.SaveAsImage(i, PdfImageType.Bitmap, 500, 500);
    
                    //Save images as PNG format to a specified folder
                    String file = String.Format("Image\\ToImage-{0}.png", i);
                    image.Save(file, ImageFormat.Png);
    
                }
            }
        }
    }

C#/VB.NET: Convert PDF to Images (JPG, PNG, BMP)

Solicitar uma licença temporária

Se você deseja remover a mensagem de avaliação dos documentos gerados ou se livrar das limitações de função, solicite uma licença de avaliação de 30 dias para você.

Veja também

Преимущество PDF-файлов в том, что они очень интерактивны и их легко передавать, но в некоторых случаях также необходимо преобразовать PDF в изображения для встраивания в веб-страницы или отображения на некоторых платформах, которые не поддерживают формат PDF. В этой статье вы узнаете, как конвертировать PDF в форматы изображений JPG, PNG или BMP на C# и VB.NET с помощью Spire.PDF for .NET.

Установите Spire.PDF for .NET

Для начала вам нужно добавить файлы DLL, включенные в пакет Spire.PDF для .NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.

PM> Install-Package Spire.PDF 

Преобразование определенной страницы PDF в изображение на C# и VB.NET

Spire.PDF for .NET предлагает метод PdfDocument.SaveAsImage() для преобразования определенной страницы PDF в изображение. Затем вы можете сохранить изображение в формате JPEG, PNG, BMP, EMF, GIF или WMF. Ниже приведены подробные шаги.

  • Создайте экземпляр документа.
  • Загрузите образец PDF-документа с помощью метода PdfDocument.LoadFromFile().
  • Преобразуйте определенную страницу в изображение и установите разрешение изображения с помощью метода PdfDocument.SaveAsImage(int pageIndex, PdfImageType type, int dpiX, int dpiY).
  • Сохраните изображение в виде файла PNG, JPG или BMP, используя метод Image.Save(string filename, ImageFormat format).
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using System.Drawing;
    using System.Drawing.Imaging;
    
    namespace PDFtoImage
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
    
                //Load a sample PDF document
                pdf.LoadFromFile("E:\\Files\\input.pdf");
    
                //Convert the first page to an image and set the image Dpi
                Image image = pdf.SaveAsImage(0, PdfImageType.Bitmap, 500, 500);
    
                //Save the image as a JPG file
                image.Save("ToJPG.jpg", ImageFormat.Jpeg);
    
                //Save the image as a PNG file
                //image.Save("ToPNG.png", ImageFormat.Png);
    
                //Save the image as a BMP file
                //image.Save("ToBMP.bmp", ImageFormat.Bmp);
            }
        }
    }

C#/VB.NET: Convert PDF to Images (JPG, PNG, BMP)

Преобразование всего документа PDF в несколько изображений в C# и VB.NET

Если вы хотите преобразовать весь документ PDF в несколько отдельных изображений, вы можете просмотреть все страницы в PDF, а затем сохранить их как изображения JPG, PNG или BMP. Ниже приведены подробные шаги.

  • Создайте экземпляр PdfDocument.
  • Загрузите образец PDF-документа с помощью метода PdfDocument.LoadFromFile().
  • Перебрать все страницы документа и установить DPI изображения при преобразовании их в изображения с помощью метода PdfDocument.SaveAsImage(int pageIndex, PdfImageType type, int dpiX, int dpiY).
  • Сохраняйте изображения в виде файлов PNG с помощью метода Image.Save().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using System;
    using System.Drawing;
    using System.Drawing.Imaging;
    
    namespace PDFtoImage
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
    
                //Load a sample PDF document
                pdf.LoadFromFile("input.pdf");
    
                //Loop through each page in the PDF
                for (int i = 0; i < pdf.Pages.Count; i++)
                {
                    //Convert all pages to images and set the image Dpi
                    Image image = pdf.SaveAsImage(i, PdfImageType.Bitmap, 500, 500);
    
                    //Save images as PNG format to a specified folder
                    String file = String.Format("Image\\ToImage-{0}.png", i);
                    image.Save(file, ImageFormat.Png);
    
                }
            }
        }
    }

C#/VB.NET: Convert PDF to Images (JPG, PNG, BMP)

Подать заявку на временную лицензию

Если вы хотите удалить оценочное сообщение из сгенерированных документов или избавиться от функциональных ограничений, запросите для себя 30-дневную пробную лицензию.

Смотрите также

Instalado a través de NuGet

PM> Install-Package Spire.PDF

enlaces relacionados

Los archivos PDF tienen la ventaja de ser altamente interactivos y fáciles de transferir, pero en ciertos casos, también es necesario convertir PDF en imágenes para incrustarlas en páginas web o mostrarlas en algunas plataformas que no admiten el formato PDF. En este artículo, aprenderá a convertir PDF a formatos de imagen JPG, PNG o BMP en C# y VB.NET utilizando Spire.PDF for .NET.

Instalar Spire.PDF for .NET

Para empezar, debe agregar los archivos DLL incluidos en el paquete Spire.PDF para .NET como referencias en su proyecto .NET. Los archivos DLL se pueden descargar desde este enlace o instalar a través de NuGet.

PM> Install-Package Spire.PDF 

Convierta una página PDF específica en una imagen en C# y VB.NET

Spire.PDF for .NET ofrece el método PdfDocument.SaveAsImage() para convertir una página particular en PDF en una imagen. Luego, puede guardar la imagen como un archivo JPEG, PNG, BMP, EMF, GIF o WMF. Los siguientes son los pasos detallados.

  • Cree una instancia de documento.
  • Cargue un documento PDF de muestra utilizando el método PdfDocument.LoadFromFile().
  • Convierta una página específica en una imagen y configure los Dpi de la imagen usando el método PdfDocument.SaveAsImage(int pageIndex, PdfImageType type, int dpiX, int dpiY).
  • Guarde la imagen como un archivo PNG, JPG o BMP utilizando el método Image.Save (nombre de archivo de cadena, formato ImageFormat).
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using System.Drawing;
    using System.Drawing.Imaging;
    
    namespace PDFtoImage
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
    
                //Load a sample PDF document
                pdf.LoadFromFile("E:\\Files\\input.pdf");
    
                //Convert the first page to an image and set the image Dpi
                Image image = pdf.SaveAsImage(0, PdfImageType.Bitmap, 500, 500);
    
                //Save the image as a JPG file
                image.Save("ToJPG.jpg", ImageFormat.Jpeg);
    
                //Save the image as a PNG file
                //image.Save("ToPNG.png", ImageFormat.Png);
    
                //Save the image as a BMP file
                //image.Save("ToBMP.bmp", ImageFormat.Bmp);
            }
        }
    }

C#/VB.NET: Convert PDF to Images (JPG, PNG, BMP)

Convierta un documento PDF completo en varias imágenes en C# y VB.NET

Si desea convertir todo el documento PDF en varias imágenes individuales, puede recorrer todas las páginas del PDF y luego guardarlas como imágenes JPG, PNG o BMP. Los siguientes son los pasos detallados.

  • Cree una instancia de PdfDocument.
  • Cargue un documento PDF de muestra utilizando el método PdfDocument.LoadFromFile().
  • Recorra todas las páginas del documento y configure los Dpi de la imagen al convertirlos en imágenes usando el método PdfDocument.SaveAsImage(int pageIndex, PdfImageType type, int dpiX, int dpiY).
  • Guarde las imágenes como archivos PNG utilizando el método Image.Save().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using System;
    using System.Drawing;
    using System.Drawing.Imaging;
    
    namespace PDFtoImage
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
    
                //Load a sample PDF document
                pdf.LoadFromFile("input.pdf");
    
                //Loop through each page in the PDF
                for (int i = 0; i < pdf.Pages.Count; i++)
                {
                    //Convert all pages to images and set the image Dpi
                    Image image = pdf.SaveAsImage(i, PdfImageType.Bitmap, 500, 500);
    
                    //Save images as PNG format to a specified folder
                    String file = String.Format("Image\\ToImage-{0}.png", i);
                    image.Save(file, ImageFormat.Png);
    
                }
            }
        }
    }

C#/VB.NET: Convert PDF to Images (JPG, PNG, BMP)

Solicitar una Licencia Temporal

Si desea eliminar el mensaje de evaluación de los documentos generados o deshacerse de las limitaciones de la función, solicite una licencia de prueba de 30 días para usted.

Ver también

PDF 파일은 대화형이며 전송하기 쉽다는 장점이 있지만 경우에 따라 웹 페이지에 삽입하거나 PDF 형식을 지원하지 않는 일부 플랫폼에 표시하기 위해 PDF를 이미지로 변환해야 할 수도 있습니다. 이 기사에서는 .NET용 Spire.PDF를 사용하여 C# 및 VB.NET에서 PDF를 JPG, PNG 또는 BMP 이미지 형식으로 변환하는 방법을 배웁니다.

Spire.PDF for .NET 설치

먼저 Spire.PDF for .NET 패키지에 포함된 DLL 파일을 .NET 프로젝트의 참조로 추가해야 합니다. DLL 파일은 이 링크에서 다운로드하거나 NuGet을 통해 설치할 수 있습니다.

PM> Install-Package Spire.PDF 

C# 및 VB.NET에서 특정 PDF 페이지를 이미지로 변환

.NET용 Spire.PDF는 PDF의 특정 페이지를 이미지로 변환하는 PdfDocument.SaveAsImage() 메서드를 제공합니다. 그런 다음 이미지를 JPEG, PNG, BMP, EMF, GIF 또는 WMF 파일로 저장할 수 있습니다. 다음은 세부 단계입니다.

  • 문서 인스턴스를 만듭니다.
  • PdfDocument.LoadFromFile() 메서드를 사용하여 샘플 PDF 문서를 로드합니다.
  • 특정 페이지를 이미지로 변환하고 PdfDocument.SaveAsImage(int pageIndex, PdfImageType type, int dpiX, int dpiY) 메서드를 사용하여 이미지 Dpi를 설정합니다.
  • Image.Save(문자열 파일 이름, ImageFormat 형식) 메서드를 사용하여 이미지를 PNG, JPG 또는 BMP 파일로 저장합니다.
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using System.Drawing;
    using System.Drawing.Imaging;
    
    namespace PDFtoImage
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
    
                //Load a sample PDF document
                pdf.LoadFromFile("E:\\Files\\input.pdf");
    
                //Convert the first page to an image and set the image Dpi
                Image image = pdf.SaveAsImage(0, PdfImageType.Bitmap, 500, 500);
    
                //Save the image as a JPG file
                image.Save("ToJPG.jpg", ImageFormat.Jpeg);
    
                //Save the image as a PNG file
                //image.Save("ToPNG.png", ImageFormat.Png);
    
                //Save the image as a BMP file
                //image.Save("ToBMP.bmp", ImageFormat.Bmp);
            }
        }
    }

C#/VB.NET: Convert PDF to Images (JPG, PNG, BMP)

C# 및 VB.NET에서 전체 PDF 문서를 여러 이미지로 변환

전체 PDF 문서를 여러 개별 이미지로 변환하려는 경우 PDF의 모든 페이지를 반복한 다음 JPG, PNG 또는 BMP 이미지로 저장할 수 있습니다. 다음은 세부 단계입니다.

  • PdfDocument 인스턴스를 만듭니다.
  • PdfDocument.LoadFromFile() 메서드를 사용하여 샘플 PDF 문서를 로드합니다.
  • 문서의 모든 페이지를 반복하고 PdfDocument.SaveAsImage(int pageIndex, PdfImageType type, int dpiX, int dpiY) 메서드를 사용하여 이미지로 변환할 때 이미지 Dpi를 설정합니다.
  • Image.Save() 메서드를 사용하여 이미지를 PNG 파일로 저장합니다.
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using System;
    using System.Drawing;
    using System.Drawing.Imaging;
    
    namespace PDFtoImage
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
    
                //Load a sample PDF document
                pdf.LoadFromFile("input.pdf");
    
                //Loop through each page in the PDF
                for (int i = 0; i < pdf.Pages.Count; i++)
                {
                    //Convert all pages to images and set the image Dpi
                    Image image = pdf.SaveAsImage(i, PdfImageType.Bitmap, 500, 500);
    
                    //Save images as PNG format to a specified folder
                    String file = String.Format("Image\\ToImage-{0}.png", i);
                    image.Save(file, ImageFormat.Png);
    
                }
            }
        }
    }

C#/VB.NET: Convert PDF to Images (JPG, PNG, BMP)

임시 면허 신청

생성된 문서에서 평가 메시지를 제거하거나 기능 제한을 제거하려면 30일 평가판 라이센스를 직접 요청하십시오.

또한보십시오

Installato tramite NuGet

PM> Install-Package Spire.PDF

Link correlati

I file PDF hanno il vantaggio di essere altamente interattivi e facili da trasferire, ma in alcuni casi è anche necessario convertire i PDF in immagini per l'incorporamento nelle pagine Web o la visualizzazione su alcune piattaforme che non supportano il formato PDF. In questo articolo imparerai come convertire PDF in formati immagine JPG, PNG o BMP in C# e VB.NET utilizzando Spire.PDF for .NET.

Installa Spire.PDF for .NET

Per cominciare, è necessario aggiungere i file DLL inclusi nel pacchetto Spire.PDF for.NET come riferimenti nel progetto .NET. I file DLL possono essere scaricati da questo collegamento o installati tramite NuGet.

PM> Install-Package Spire.PDF 

Converti una pagina PDF specifica in un'immagine in C# e VB.NET

Spire.PDF for .NET offre il metodo PdfDocument.SaveAsImage() per convertire una particolare pagina in PDF in un'immagine. Quindi, puoi salvare l'immagine come file JPEG, PNG, BMP, EMF, GIF o WMF. Di seguito sono riportati i passaggi dettagliati.

  • Crea un'istanza di Documento.
  • Carica un documento PDF di esempio utilizzando il metodo PdfDocument.LoadFromFile().
  • Converti una pagina specifica in un'immagine e imposta i Dpi dell'immagine utilizzando il metodo PdfDocument.SaveAsImage(int pageIndex, PdfImageType type, int dpiX, int dpiY).
  • Salvare l'immagine come file PNG, JPG o BMP utilizzando il metodo Image.Save(string filename, ImageFormat format).
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using System.Drawing;
    using System.Drawing.Imaging;
    
    namespace PDFtoImage
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
    
                //Load a sample PDF document
                pdf.LoadFromFile("E:\\Files\\input.pdf");
    
                //Convert the first page to an image and set the image Dpi
                Image image = pdf.SaveAsImage(0, PdfImageType.Bitmap, 500, 500);
    
                //Save the image as a JPG file
                image.Save("ToJPG.jpg", ImageFormat.Jpeg);
    
                //Save the image as a PNG file
                //image.Save("ToPNG.png", ImageFormat.Png);
    
                //Save the image as a BMP file
                //image.Save("ToBMP.bmp", ImageFormat.Bmp);
            }
        }
    }

C#/VB.NET: Convert PDF to Images (JPG, PNG, BMP)

Converti un intero documento PDF in più immagini in C# e VB.NET

Se desideri convertire l'intero documento PDF in più immagini singole, puoi scorrere tutte le pagine del PDF e quindi salvarle come immagini JPG, PNG o BMP. Di seguito sono riportati i passaggi dettagliati.

  • Creare un'istanza PdfDocument.
  • Carica un documento PDF di esempio utilizzando il metodo PdfDocument.LoadFromFile().
  • Passa in rassegna tutte le pagine del documento e imposta i Dpi dell'immagine durante la conversione in immagini utilizzando il metodo PdfDocument.SaveAsImage(int pageIndex, PdfImageType type, int dpiX, int dpiY).
  • Salva le immagini come file PNG usando il metodo Image.Save().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using System;
    using System.Drawing;
    using System.Drawing.Imaging;
    
    namespace PDFtoImage
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument instance
                PdfDocument pdf = new PdfDocument();
    
                //Load a sample PDF document
                pdf.LoadFromFile("input.pdf");
    
                //Loop through each page in the PDF
                for (int i = 0; i < pdf.Pages.Count; i++)
                {
                    //Convert all pages to images and set the image Dpi
                    Image image = pdf.SaveAsImage(i, PdfImageType.Bitmap, 500, 500);
    
                    //Save images as PNG format to a specified folder
                    String file = String.Format("Image\\ToImage-{0}.png", i);
                    image.Save(file, ImageFormat.Png);
    
                }
            }
        }
    }

C#/VB.NET: Convert PDF to Images (JPG, PNG, BMP)

Richiedi una licenza temporanea

Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni delle funzioni, richiedi una licenza di prova di 30 giorni per te stesso.

Guarda anche

Wednesday, 21 June 2023 10:28

Spire.Office for C++ 8.6.0 is released

We are excited to announce the release of Spire.Office for C++ 8.6.0. In this version, Spire.Doc for C++, Spire.XLS for C++, Spire.Presentation for C++, and Spire.PDF for C++ fix the issue that the application threw exception while applying license to a program that used two or more of the C++ products and loaded files with stream. More details are listed below.

Click the link to download Spire.Office for C++ 8.6.0:

Here are the changes made in this release

Spire.Doc for C++, Spire.XLS for C++, Spire.Presentation for C++, and Spire.PDF for C++ fix the issue that the application threw exception while applying license to a program that used two or more of the C++ products and loaded files with stream.

We are excited to announce the release of Spire.Doc 11.6.1. This version enhances the conversion from Word to PDF and HTML. Besides, many known issues are fixed in this version, such as the issue that updating mail merge fields failed. More details are listed below.

Here is a list of changes made in this release

Category ID Description
Bug SPIREDOC-9031 Fixes the issue that he obtained value of the text field containing the return mark is incorrect.
Bug SPIREDOC-9285 Fixes the issue that System.ArgumentException exception was thrown during document comparison.
Bug SPIREDOC-9339 Fixes the issue that System.ArgumentException exception was thrown during Word to HTML conversion.
Bug SPIREDOC-9365 Fixes the issue that updating mail merge fields failed.
Bug SPIREDOC-9379 Fixes the issue that replacing text that ends with a number by setting the wholeWord parameter to true does not work.
Bug SPIREDOC-9396 Fixes the issue that there was inconsistent text alignment in some parts of the document after converting Word to PDF.
Bug SPIREDOC-9430 Fixes the issue that symbol position shifted upwards after converting Word to PDF.
Click the link to download Spire.Doc 11.6.1:
More information of Spire.Doc new release or hotfix:

We are excited to announce the release of Spire.XLS for Java 13.6.0. This version enhances the conversion from Excel to PDF and images. Additionally, some known issues are fixed, such as the issue that the horizontal coordinate of the chart changed after adding an image watermark. More details are listed below.

Here is a list of changes made in this release

Category ID Description
Bug SPIREXLS-4611 Fixes the issue that the font effects were inconsistent when converting Excel to images.
Bug SPIREXLS-4639 Fixes the issue that the superscript and subscript format was lost when converting Excel to images.
Bug SPIREXLS-4642 Fixes the issue that the horizontal coordinate of the chart changed after adding an image watermark.
Bug SPIREXLS-4650 Fixes the issue that the program hangs when loading Excel documents.
Bug SPIREXLS-4669 Fixes the issue that setting the background color of the pivot table column name field failed.
Bug SPIREXLS-4671 Fixes the issue that the document data lost after adding an image watermark.
Bug SPIREXLS-4679 Fixes the issue that the memory overflow exception was thrown when converting Excel to PDF.
Bug SPIREXLS-4680 Fixes the issue that the decimal place retention in numeric charts was inconsistent when converting them to images.
Bug SPIREXLS-4682 Fixes the issue that the program threw java.lang.ClassCastException exception when loading an Excel document.
Bug SPIREXLS-4685 Fixes the issue that the result file failed to open after adding the LOG function.
Bug SPIREXLS-4687 Fixes the issue that the style changed when loading and saving an et format file.
Bug SPIREXLS-4688 Fixes the issue that the chart coordinate axis format changed when loading and saving an et format file.
Bug SPIREXLS-4736 Fixes the issue that the program threw java.lang.ClassFormatError exception when converting Excel to PDF.
Click the link to download Spire.XLS for Java 13.6.0:

We are glad to announce the release of Spire.Presentation 7.12.1. This version fixes the issue that the content was lost after saving PowerPoint slide as Image. More details are listed below.

Here is a list of changes made in this release

Category ID Description
Bug SPIREPPT-2109 Fixes the issue that the content was lost after saving PowerPoint slide as Image.
Click the link below to download Spire.Presentation 7.12.1
More information of Spire.Presentation new release or hotfix: