PDF 문서가 비즈니스에서 점점 더 인기를 끌면서 문서의 신뢰성을 보장하는 것이 주요 관심사가 되었습니다. 인증서 기반 서명으로 PDF에 서명하면 콘텐츠를 보호할 수 있으며 문서에 서명하거나 승인한 사람을 다른 사람에게 알릴 수도 있습니다. 이 기사에서는 다음 방법을 배웁니다 보이지 않거나 보이는 서명을 사용하여 PDF에 디지털 서명을 하고, 그리고 어떻게 PDF에서 디지털 서명 제거 Spire.PDF for .NET 사용합니다.

Spire.PDF for .NET 설치

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

PM> Install-Package Spire.PDF

PDF에 보이지 않는 디지털 서명 추가

다음은 Spire.PDF for .NET 사용하여 PDF에 보이지 않는 디지털 서명을 추가하는 단계입니다.

  • PdfDocument 개체를 만듭니다.
  • PdfDocument.LoadFromFile() 메서드를 사용하여 샘플 PDF 파일을 로드합니다.
  • PdfCertificate 객체를 초기화하는 동안 pfx 인증서 파일을 로드합니다.
  • 인증서를 기반으로 PdfSignature 개체를 만듭니다.
  • PdfSignature 개체를 통해 문서 권한을 설정합니다.
  • PdfDocument.SaveToFile() 메서드를 사용하여 문서를 다른 PDF 파일에 저장합니다.
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    
    namespace AddInvisibleSignature
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
    
                //Load a sample PDF file
                doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");
    
                //Load the certificate
                PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue");
    
                //Create a PdfSignature object
                PdfSignature signature = new PdfSignature(doc, doc.Pages[doc.Pages.Count - 1], cert, "MySignature");
    
                //Set the document permission to forbid changes but allow form fill
                signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges | PdfCertificationFlags.AllowFormFill;
    
                //Save to another PDF file
                doc.SaveToFile("InvisibleSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Add or Remove Digital Signatures in PDF

PDF에 보이는 디지털 서명 추가

다음은 Spire.PDF for .NET 사용하여 PDF에 눈에 보이는 디지털 서명을 추가하는 단계입니다.

  • PdfDocument 개체를 만듭니다.
  • PdfDocument.LoadFromFile() 메서드를 사용하여 샘플 PDF 파일을 로드합니다.
  • PdfCertificate 객체를 초기화하는 동안 pfx 인증서 파일을 로드합니다.
  • PdfSignature 개체를 만들고 문서에서 위치와 크기를 지정합니다.
  • 날짜, 이름, 위치, 사유, 자필 서명 이미지, 문서 권한 등 서명 세부 사항을 설정합니다.
  • PdfDocument.SaveToFile() 메서드를 사용하여 문서를 다른 PDF 파일에 저장합니다.
  • C#
  • VB.NET
using System;
    using System.Drawing;
    using Spire.Pdf;
    using Spire.Pdf.Security;
    using Spire.Pdf.Graphics;
    
    namespace AddVisibleSignature
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
    
                //Load a sample PDF file
                doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");
    
                //Load the certificate
                PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue");
    
                //Create a PdfSignature object and specify its position and size
                PdfSignature signature = new PdfSignature(doc, doc.Pages[doc.Pages.Count - 1], cert, "MySignature");
                RectangleF rectangleF = new RectangleF(doc.Pages[0].ActualSize.Width - 260 - 54 , 200, 260, 110);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to ImageAndSignDetail
                signature.GraphicsMode = GraphicMode.SignImageAndSignDetail;
    
                //Set the signature content
                signature.NameLabel = "Signer:";
                signature.Name = "Gary";
                signature.ContactInfoLabel = "Phone:";
                signature.ContactInfo = "0123456";
                signature.DateLabel = "Date:";
                signature.Date = DateTime.Now;
                signature.LocationInfoLabel = "Location:";
                signature.LocationInfo = "USA";
                signature.ReasonLabel = "Reason:";
                signature.Reason = "I am the author";
                signature.DistinguishedNameLabel = "DN:";
                signature.DistinguishedName = signature.Certificate.IssuerName.Name;
    
                //Set the signature image source
                signature.SignImageSource = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\handwrittingSignature.png");
    
                //Set the signature font
                signature.SignDetailsFont = new PdfTrueTypeFont(new Font("Arial Unicode MS", 12f, FontStyle.Regular));
    
                //Set the document permission to forbid changes but allow form fill
                signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges | PdfCertificationFlags.AllowFormFill;
    
                //Save to file
                doc.SaveToFile("VisiableSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Add or Remove Digital Signatures in PDF

PDF에서 디지털 서명 제거

다음은 Spire.PDF for .NET 사용하여 PDF에서 디지털 서명을 제거하는 단계입니다.

  • PdfDocument 개체를 만듭니다.
  • PdfDocument.Form 속성을 통해 문서에서 양식 위젯을 가져옵니다.
  • 위젯을 반복하고 특정 위젯이 PdfSignatureFieldWidget인지 확인합니다.
  • PdfFieldCollection.RemoveAt() 메서드를 사용하여 서명 위젯을 제거합니다.
  • PdfDocument.SaveToFile() 메서드를 사용하여 문서를 다른 PDF 파일에 저장합니다.
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Widget;
    
    namespace RemoveSignature
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument("C:\\Users\\Administrator\\Desktop\\VisiableSignature.pdf");
    
                //Get form widgets from the document
                PdfFormWidget widgets = doc.Form as PdfFormWidget;
    
                //Loop through the widgets
                for (int i = 0; i < widgets.FieldsWidget.List.Count; i++)
                {
                    //Get the specific widget
                    PdfFieldWidget widget = widgets.FieldsWidget.List[i] as PdfFieldWidget;
    
                    //Determine if the widget is a PdfSignatureFieldWidget
                    if (widget is PdfSignatureFieldWidget)
                    {
                        //Remove the widget
                        widgets.FieldsWidget.RemoveAt(i);
                    }
                }
    
                //Save the document to another PDF file
                doc.SaveToFile("RemoveSignatures.pdf");
            }
        }
    }

임시 라이센스 신청

생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.

또한보십시오

Poiché i documenti PDF diventano sempre più popolari nel mondo degli affari, garantirne l'autenticità è diventata una preoccupazione fondamentale. Firmare i PDF con una firma basata su certificato può proteggere il contenuto e anche far sapere ad altri chi ha firmato o approvato il documento. In questo articolo imparerai come farlo firmare digitalmente i PDF con una firma invisibile o visibile e come rimuovere le firme digitali dai PDF utilizzando Spire.PDF for .NET.

Installa Spire.PDF for .NET

Per cominciare, devi aggiungere i file DLL inclusi nel pacchetto Spire.PDF for .NET come riferimenti nel tuo progetto .NET. I file DLL possono essere scaricati da questo link o installato tramite NuGet.

PM> Install-Package Spire.PDF

Aggiungi una firma digitale invisibile al PDF

Di seguito sono riportati i passaggi per aggiungere una firma digitale invisibile al PDF utilizzando Spire.PDF for .NET.

  • Crea un oggetto PdfDocument.
  • Carica un file PDF di esempio utilizzando il metodo PdfDocument.LoadFromFile().
  • Carica un file di certificato pfx durante l'inizializzazione dell'oggetto PdfCertificate.
  • Crea un oggetto PdfSignature basato sul certificato.
  • Imposta i permessi del documento tramite l'oggetto PdfSignature.
  • Salva il documento in un altro file PDF utilizzando il metodo PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    
    namespace AddInvisibleSignature
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
    
                //Load a sample PDF file
                doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");
    
                //Load the certificate
                PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue");
    
                //Create a PdfSignature object
                PdfSignature signature = new PdfSignature(doc, doc.Pages[doc.Pages.Count - 1], cert, "MySignature");
    
                //Set the document permission to forbid changes but allow form fill
                signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges | PdfCertificationFlags.AllowFormFill;
    
                //Save to another PDF file
                doc.SaveToFile("InvisibleSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Add or Remove Digital Signatures in PDF

Aggiungi una firma digitale visibile al PDF

Di seguito sono riportati i passaggi per aggiungere una firma digitale visibile al PDF utilizzando Spire.PDF for .NET.

  • Crea un oggetto PdfDocument.
  • Carica un file PDF di esempio utilizzando il metodo PdfDocument.LoadFromFile().
  • Carica un file di certificato pfx durante l'inizializzazione dell'oggetto PdfCertificate.
  • Crea un oggetto PdfSignature e specificane la posizione e le dimensioni sul documento.
  • Imposta i dettagli della firma tra cui data, nome, posizione, motivo, immagine della firma scritta a mano e autorizzazioni del documento.
  • Salva il documento in un altro file PDF utilizzando il metodo PdfDocument.SaveToFile().
  • C#
  • VB.NET
using System;
    using System.Drawing;
    using Spire.Pdf;
    using Spire.Pdf.Security;
    using Spire.Pdf.Graphics;
    
    namespace AddVisibleSignature
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
    
                //Load a sample PDF file
                doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");
    
                //Load the certificate
                PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue");
    
                //Create a PdfSignature object and specify its position and size
                PdfSignature signature = new PdfSignature(doc, doc.Pages[doc.Pages.Count - 1], cert, "MySignature");
                RectangleF rectangleF = new RectangleF(doc.Pages[0].ActualSize.Width - 260 - 54 , 200, 260, 110);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to ImageAndSignDetail
                signature.GraphicsMode = GraphicMode.SignImageAndSignDetail;
    
                //Set the signature content
                signature.NameLabel = "Signer:";
                signature.Name = "Gary";
                signature.ContactInfoLabel = "Phone:";
                signature.ContactInfo = "0123456";
                signature.DateLabel = "Date:";
                signature.Date = DateTime.Now;
                signature.LocationInfoLabel = "Location:";
                signature.LocationInfo = "USA";
                signature.ReasonLabel = "Reason:";
                signature.Reason = "I am the author";
                signature.DistinguishedNameLabel = "DN:";
                signature.DistinguishedName = signature.Certificate.IssuerName.Name;
    
                //Set the signature image source
                signature.SignImageSource = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\handwrittingSignature.png");
    
                //Set the signature font
                signature.SignDetailsFont = new PdfTrueTypeFont(new Font("Arial Unicode MS", 12f, FontStyle.Regular));
    
                //Set the document permission to forbid changes but allow form fill
                signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges | PdfCertificationFlags.AllowFormFill;
    
                //Save to file
                doc.SaveToFile("VisiableSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Add or Remove Digital Signatures in PDF

Rimuovere le firme digitali dai PDF

Di seguito sono riportati i passaggi per rimuovere le firme digitali dal PDF utilizzando Spire.PDF for .NET.

  • Crea un oggetto PdfDocument.
  • Ottieni i widget del modulo dal documento tramite la proprietà PdfDocument.Form.
  • Passa in rassegna i widget e determina se un widget specifico è un PdfSignatureFieldWidget.
  • Rimuovere il widget della firma utilizzando il metodo PdfFieldCollection.RemoveAt().
  • Salva il documento in un altro file PDF utilizzando il metodo PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Widget;
    
    namespace RemoveSignature
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument("C:\\Users\\Administrator\\Desktop\\VisiableSignature.pdf");
    
                //Get form widgets from the document
                PdfFormWidget widgets = doc.Form as PdfFormWidget;
    
                //Loop through the widgets
                for (int i = 0; i < widgets.FieldsWidget.List.Count; i++)
                {
                    //Get the specific widget
                    PdfFieldWidget widget = widgets.FieldsWidget.List[i] as PdfFieldWidget;
    
                    //Determine if the widget is a PdfSignatureFieldWidget
                    if (widget is PdfSignatureFieldWidget)
                    {
                        //Remove the widget
                        widgets.FieldsWidget.RemoveAt(i);
                    }
                }
    
                //Save the document to another PDF file
                doc.SaveToFile("RemoveSignatures.pdf");
            }
        }
    }

Richiedi una licenza temporanea

Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni della funzione, per favore richiedere una licenza di prova di 30 giorni per te.

Guarda anche

Alors que les documents PDF deviennent de plus en plus populaires dans les entreprises, garantir leur authenticité est devenu une préoccupation majeure. La signature de PDF avec une signature basée sur un certificat peut protéger le contenu et également permettre aux autres de savoir qui a signé ou approuvé le document. Dans cet article, vous apprendrez comment signer numériquement un PDF avec une signature invisible ou visible, et comment supprimer les signatures numériques d'un PDF à l'aide de Spire.PDF for .NET.

Installer Spire.PDF for .NET

Pour commencer, vous devez ajouter les fichiers DLL inclus dans le package Spire.PDF for.NET comme 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.PDF

Ajouter une signature numérique invisible au PDF

Voici les étapes pour ajouter une signature numérique invisible au PDF à l'aide de Spire.PDF for .NET.

  • Créez un objet PdfDocument.
  • Chargez un exemple de fichier PDF à l'aide de la méthode PdfDocument.LoadFromFile().
  • Chargez un fichier de certificat pfx lors de l'initialisation de l'objet PdfCertificate.
  • Créez un objet PdfSignature basé sur le certificat.
  • Définissez les autorisations du document via l'objet PdfSignature.
  • Enregistrez le document dans un autre fichier PDF à l'aide de la méthode PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Security;
    
    namespace AddInvisibleSignature
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
    
                //Load a sample PDF file
                doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");
    
                //Load the certificate
                PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue");
    
                //Create a PdfSignature object
                PdfSignature signature = new PdfSignature(doc, doc.Pages[doc.Pages.Count - 1], cert, "MySignature");
    
                //Set the document permission to forbid changes but allow form fill
                signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges | PdfCertificationFlags.AllowFormFill;
    
                //Save to another PDF file
                doc.SaveToFile("InvisibleSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Add or Remove Digital Signatures in PDF

Ajouter une signature numérique visible au PDF

Voici les étapes pour ajouter une signature numérique visible au PDF à l'aide de Spire.PDF for .NET.

  • Créez un objet PdfDocument.
  • Chargez un exemple de fichier PDF à l'aide de la méthode PdfDocument.LoadFromFile().
  • Chargez un fichier de certificat pfx lors de l'initialisation de l'objet PdfCertificate.
  • Créez un objet PdfSignature et spécifiez sa position et sa taille sur le document.
  • Définissez les détails de la signature, notamment la date, le nom, le lieu, le motif, l'image de la signature manuscrite et les autorisations du document.
  • Enregistrez le document dans un autre fichier PDF à l'aide de la méthode PdfDocument.SaveToFile().
  • C#
  • VB.NET
using System;
    using System.Drawing;
    using Spire.Pdf;
    using Spire.Pdf.Security;
    using Spire.Pdf.Graphics;
    
    namespace AddVisibleSignature
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
    
                //Load a sample PDF file
                doc.LoadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");
    
                //Load the certificate
                PdfCertificate cert = new PdfCertificate("C:\\Users\\Administrator\\Desktop\\MyCertificate.pfx", "e-iceblue");
    
                //Create a PdfSignature object and specify its position and size
                PdfSignature signature = new PdfSignature(doc, doc.Pages[doc.Pages.Count - 1], cert, "MySignature");
                RectangleF rectangleF = new RectangleF(doc.Pages[0].ActualSize.Width - 260 - 54 , 200, 260, 110);
                signature.Bounds = rectangleF;
                signature.Certificated = true;
    
                //Set the graphics mode to ImageAndSignDetail
                signature.GraphicsMode = GraphicMode.SignImageAndSignDetail;
    
                //Set the signature content
                signature.NameLabel = "Signer:";
                signature.Name = "Gary";
                signature.ContactInfoLabel = "Phone:";
                signature.ContactInfo = "0123456";
                signature.DateLabel = "Date:";
                signature.Date = DateTime.Now;
                signature.LocationInfoLabel = "Location:";
                signature.LocationInfo = "USA";
                signature.ReasonLabel = "Reason:";
                signature.Reason = "I am the author";
                signature.DistinguishedNameLabel = "DN:";
                signature.DistinguishedName = signature.Certificate.IssuerName.Name;
    
                //Set the signature image source
                signature.SignImageSource = PdfImage.FromFile("C:\\Users\\Administrator\\Desktop\\handwrittingSignature.png");
    
                //Set the signature font
                signature.SignDetailsFont = new PdfTrueTypeFont(new Font("Arial Unicode MS", 12f, FontStyle.Regular));
    
                //Set the document permission to forbid changes but allow form fill
                signature.DocumentPermissions = PdfCertificationFlags.ForbidChanges | PdfCertificationFlags.AllowFormFill;
    
                //Save to file
                doc.SaveToFile("VisiableSignature.pdf");
                doc.Close();
            }
        }
    }

C#/VB.NET: Add or Remove Digital Signatures in PDF

Supprimer les signatures numériques du PDF

Voici les étapes pour supprimer les signatures numériques d'un PDF à l'aide de Spire.PDF for .NET.

  • Créez un objet PdfDocument.
  • Obtenez des widgets de formulaire à partir du document via la propriété PdfDocument.Form.
  • Parcourez les widgets et déterminez si un widget spécifique est un PdfSignatureFieldWidget.
  • Supprimez le widget de signature à l'aide de la méthode PdfFieldCollection.RemoveAt().
  • Enregistrez le document dans un autre fichier PDF à l'aide de la méthode PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Widget;
    
    namespace RemoveSignature
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument("C:\\Users\\Administrator\\Desktop\\VisiableSignature.pdf");
    
                //Get form widgets from the document
                PdfFormWidget widgets = doc.Form as PdfFormWidget;
    
                //Loop through the widgets
                for (int i = 0; i < widgets.FieldsWidget.List.Count; i++)
                {
                    //Get the specific widget
                    PdfFieldWidget widget = widgets.FieldsWidget.List[i] as PdfFieldWidget;
    
                    //Determine if the widget is a PdfSignatureFieldWidget
                    if (widget is PdfSignatureFieldWidget)
                    {
                        //Remove the widget
                        widgets.FieldsWidget.RemoveAt(i);
                    }
                }
    
                //Save the document to another PDF file
                doc.SaveToFile("RemoveSignatures.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 fonctionnelles, veuillez demander une licence d'essai de 30 jours pour toi.

Voir également

Installed via NuGet

PM> Install-Package Spire.PDF

Related Links

If you have multiple images that you want to combine into one file for easier distribution or storage, converting them into a single PDF document is a great solution. This process not only saves space but also ensures that all your images are kept together in one file, making it convenient to share or transfer. In this article, you will learn how to combine several images into a single PDF document in C# and VB.NET using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Combine Multiple Images into a Single PDF in C# and VB.NET

In order to convert all the images in a folder to a PDF, we iterate through each image, add a new page to the PDF with the same size as the image, and then draw the image onto the new page. The following are the detailed steps.

  • Create a PdfDocument object.
  • Set the page margins to zero using PdfDocument.PageSettings.SetMargins() method.
  • Get the folder where the images are stored.
  • Iterate through each image file in the folder, and get the width and height of a specific image.
  • Add a new page that has the same width and height as the image to the PDF document using PdfDocument.Pages.Add() method.
  • Draw the image on the page using PdfPageBase.Canvas.DrawImage() method.
  • Save the document using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using System.Drawing;
    
    namespace ConvertMultipleImagesIntoPdf
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
    
                //Set the page margins to 0
                doc.PageSettings.SetMargins(0);
    
                //Get the folder where the images are stored
                DirectoryInfo folder = new DirectoryInfo(@"C:\Users\Administrator\Desktop\Images");
    
                //Iterate through the files in the folder
                foreach (FileInfo file in folder.GetFiles())
                {
                    //Load a particular image
                    Image image = Image.FromFile(file.FullName);
    
                    //Get the image width and height
                    float width = image.PhysicalDimension.Width;
                    float height = image.PhysicalDimension.Height;
    
                    //Add a page that has the same size as the image
                    PdfPageBase page = doc.Pages.Add(new SizeF(width, height));
    
                    //Create a PdfImage object based on the image
                    PdfImage pdfImage = PdfImage.FromImage(image);
    
                    //Draw image at (0, 0) of the page
                    page.Canvas.DrawImage(pdfImage, 0, 0, pdfImage.Width, pdfImage.Height);
                }
    
                //Save to file
                doc.SaveToFile("CombinaImagesToPdf.pdf");
                doc.Dispose();
            }
        }
    }

C#/VB.NET: Convert Multiple Images into a Single PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

See Also

Instalado via NuGet

PM> Install-Package Spire.PDF

Links Relacionados

Se você tiver várias imagens que deseja combinar em um arquivo para facilitar a distribuição ou armazenamento, convertê-las em um único documento PDF é uma ótima solução. Esse processo não apenas economiza espaço, mas também garante que todas as suas imagens sejam mantidas juntas em um arquivo, facilitando o compartilhamento ou a transferência. Neste artigo você aprenderá como combine várias imagens em um único documento PDF em C# e VB.NET usando Spire.PDF for .NET.

Instale 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

Combine várias imagens em um único PDF em C# e VB.NET

Para converter todas as imagens de uma pasta em PDF, iteramos cada imagem, adicionamos uma nova página ao PDF com o mesmo tamanho da imagem e, em seguida, desenhamos a imagem na nova página. A seguir estão as etapas detalhadas.

  • Crie um objeto PdfDocument.
  • Defina as margens da página como zero usando o método PdfDocument.PageSettings.SetMargins().
  • Obtenha a pasta onde as imagens estão armazenadas.
  • Itere cada arquivo de imagem na pasta e obtenha a largura e a altura de uma imagem específica.
  • Adicione uma nova página que tenha a mesma largura e altura da imagem ao documento PDF usando o método PdfDocument.Pages.Add().
  • Desenhe a imagem na página usando o método PdfPageBase.Canvas.DrawImage().
  • Salve o documento usando o método PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using System.Drawing;
    
    namespace ConvertMultipleImagesIntoPdf
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
    
                //Set the page margins to 0
                doc.PageSettings.SetMargins(0);
    
                //Get the folder where the images are stored
                DirectoryInfo folder = new DirectoryInfo(@"C:\Users\Administrator\Desktop\Images");
    
                //Iterate through the files in the folder
                foreach (FileInfo file in folder.GetFiles())
                {
                    //Load a particular image
                    Image image = Image.FromFile(file.FullName);
    
                    //Get the image width and height
                    float width = image.PhysicalDimension.Width;
                    float height = image.PhysicalDimension.Height;
    
                    //Add a page that has the same size as the image
                    PdfPageBase page = doc.Pages.Add(new SizeF(width, height));
    
                    //Create a PdfImage object based on the image
                    PdfImage pdfImage = PdfImage.FromImage(image);
    
                    //Draw image at (0, 0) of the page
                    page.Canvas.DrawImage(pdfImage, 0, 0, pdfImage.Width, pdfImage.Height);
                }
    
                //Save to file
                doc.SaveToFile("CombinaImagesToPdf.pdf");
                doc.Dispose();
            }
        }
    }

C#/VB.NET: Convert Multiple Images into a Single PDF

Solicite uma licença temporária

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

Veja também

Установлено через NuGet

PM> Install-Package Spire.PDF

Ссылки по теме

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

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

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

PM> Install-Package Spire.PDF

Объединение нескольких изображений в один PDF-файл в C# и VB.NET

Чтобы преобразовать все изображения в папке в PDF-файл, мы перебираем каждое изображение, добавляем в PDF-файл новую страницу того же размера, что и изображение, а затем рисуем изображение на новой странице. Ниже приведены подробные шаги.

  • Создайте объект PDFDocument.
  • Установите поля страницы на ноль, используя метод PdfDocument.PageSettings.SetMargins().
  • Получите папку, в которой хранятся изображения.
  • Переберите каждый файл изображения в папке и получите ширину и высоту определенного изображения.
  • Добавьте в PDF-документ новую страницу той же ширины и высоты, что и изображение, с помощью метода PdfDocument.Pages.Add().
  • Нарисуйте изображение на странице, используя метод PdfPageBase.Canvas.DrawImage().
  • Сохраните документ, используя метод PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using System.Drawing;
    
    namespace ConvertMultipleImagesIntoPdf
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
    
                //Set the page margins to 0
                doc.PageSettings.SetMargins(0);
    
                //Get the folder where the images are stored
                DirectoryInfo folder = new DirectoryInfo(@"C:\Users\Administrator\Desktop\Images");
    
                //Iterate through the files in the folder
                foreach (FileInfo file in folder.GetFiles())
                {
                    //Load a particular image
                    Image image = Image.FromFile(file.FullName);
    
                    //Get the image width and height
                    float width = image.PhysicalDimension.Width;
                    float height = image.PhysicalDimension.Height;
    
                    //Add a page that has the same size as the image
                    PdfPageBase page = doc.Pages.Add(new SizeF(width, height));
    
                    //Create a PdfImage object based on the image
                    PdfImage pdfImage = PdfImage.FromImage(image);
    
                    //Draw image at (0, 0) of the page
                    page.Canvas.DrawImage(pdfImage, 0, 0, pdfImage.Width, pdfImage.Height);
                }
    
                //Save to file
                doc.SaveToFile("CombinaImagesToPdf.pdf");
                doc.Dispose();
            }
        }
    }

C#/VB.NET: Convert Multiple Images into a Single PDF

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

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

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

Über NuGet installiert

PM> Install-Package Spire.PDF

verwandte Links

Wenn Sie mehrere Bilder haben, die Sie zur einfacheren Verteilung oder Speicherung in einer Datei kombinieren möchten, ist die Konvertierung in ein einziges PDF-Dokument eine hervorragende Lösung. Dieser Vorgang spart nicht nur Platz, sondern sorgt auch dafür, dass alle Ihre Bilder in einer Datei zusammengehalten werden, sodass sie bequem geteilt oder übertragen werden können. In diesem Artikel erfahren Sie, wie das geht Kombinieren Sie mehrere Bilder in einem einzigen PDF-Dokument in C# und VB.NET mit Spire.PDF for .NET.

Installieren Sie Spire.PDF for .NET

Zunächst müssen Sie die im Spire.PDF for.NET-Paket enthaltenen DLL-Dateien als Referenzen in Ihrem .NET-Projekt hinzufügen. Die DLL-Dateien können entweder über diesen Link heruntergeladen oder über NuGet installiert werden.

PM> Install-Package Spire.PDF

Kombinieren Sie mehrere Bilder in einer einzigen PDF-Datei in C# und VB.NET

Um alle Bilder in einem Ordner in ein PDF zu konvertieren, durchlaufen wir jedes Bild, fügen dem PDF eine neue Seite mit der gleichen Größe wie das Bild hinzu und zeichnen das Bild dann auf die neue Seite. Im Folgenden finden Sie die detaillierten Schritte.

  • Erstellen Sie ein PdfDocument-Objekt.
  • Setzen Sie die Seitenränder mit der Methode PdfDocument.PageSettings.SetMargins() auf Null.
  • Rufen Sie den Ordner ab, in dem die Bilder gespeichert sind.
  • Durchlaufen Sie jede Bilddatei im Ordner und ermitteln Sie die Breite und Höhe eines bestimmten Bildes.
  • Fügen Sie dem PDF-Dokument mit der Methode PdfDocument.Pages.Add() eine neue Seite hinzu, die dieselbe Breite und Höhe wie das Bild hat.
  • Zeichnen Sie das Bild mit der Methode PdfPageBase.Canvas.DrawImage() auf die Seite.
  • Speichern Sie das Dokument mit der Methode PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using System.Drawing;
    
    namespace ConvertMultipleImagesIntoPdf
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
    
                //Set the page margins to 0
                doc.PageSettings.SetMargins(0);
    
                //Get the folder where the images are stored
                DirectoryInfo folder = new DirectoryInfo(@"C:\Users\Administrator\Desktop\Images");
    
                //Iterate through the files in the folder
                foreach (FileInfo file in folder.GetFiles())
                {
                    //Load a particular image
                    Image image = Image.FromFile(file.FullName);
    
                    //Get the image width and height
                    float width = image.PhysicalDimension.Width;
                    float height = image.PhysicalDimension.Height;
    
                    //Add a page that has the same size as the image
                    PdfPageBase page = doc.Pages.Add(new SizeF(width, height));
    
                    //Create a PdfImage object based on the image
                    PdfImage pdfImage = PdfImage.FromImage(image);
    
                    //Draw image at (0, 0) of the page
                    page.Canvas.DrawImage(pdfImage, 0, 0, pdfImage.Width, pdfImage.Height);
                }
    
                //Save to file
                doc.SaveToFile("CombinaImagesToPdf.pdf");
                doc.Dispose();
            }
        }
    }

C#/VB.NET: Convert Multiple Images into a Single PDF

Beantragen Sie eine temporäre Lizenz

Wenn Sie die Bewertungsmeldung aus den generierten Dokumenten entfernen oder die Funktionseinschränkungen beseitigen möchten, wenden Sie sich bitte an uns Fordern Sie eine 30-Tage-Testlizenz an für sich selbst.

Siehe auch

Instalado a través de NuGet

PM> Install-Package Spire.PDF

enlaces relacionados

Si tiene varias imágenes que desea combinar en un archivo para facilitar su distribución o almacenamiento, convertirlas en un solo documento PDF es una excelente solución. Este proceso no sólo ahorra espacio sino que también garantiza que todas sus imágenes se mantengan juntas en un solo archivo, lo que hace que sea conveniente compartirlas o transferirlas. En este artículo, aprenderá cómo combine varias imágenes en un solo documento PDF en C# y VB.NET usando Spire.PDF for .NET.

Instalar Spire.PDF for .NET

Para empezar, debe agregar los archivos DLL incluidos en el paquete Spire.PDF for .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

Combine varias imágenes en un solo PDF en C# y VB.NET

Para convertir todas las imágenes de una carpeta a un PDF, recorremos cada imagen, agregamos una nueva página al PDF con el mismo tamaño que la imagen y luego dibujamos la imagen en la nueva página. Los siguientes son los pasos detallados.

  • Cree un objeto PdfDocument.
  • Establezca los márgenes de la página en cero utilizando el método PdfDocument.PageSettings.SetMargins().
  • Obtenga la carpeta donde se almacenan las imágenes.
  • Repita cada archivo de imagen en la carpeta y obtenga el ancho y alto de una imagen específica.
  • Agregue una nueva página que tenga el mismo ancho y alto que la imagen al documento PDF utilizando el método PdfDocument.Pages.Add().
  • Dibuja la imagen en la página usando el método PdfPageBase.Canvas.DrawImage().
  • Guarde el documento utilizando el método PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using System.Drawing;
    
    namespace ConvertMultipleImagesIntoPdf
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
    
                //Set the page margins to 0
                doc.PageSettings.SetMargins(0);
    
                //Get the folder where the images are stored
                DirectoryInfo folder = new DirectoryInfo(@"C:\Users\Administrator\Desktop\Images");
    
                //Iterate through the files in the folder
                foreach (FileInfo file in folder.GetFiles())
                {
                    //Load a particular image
                    Image image = Image.FromFile(file.FullName);
    
                    //Get the image width and height
                    float width = image.PhysicalDimension.Width;
                    float height = image.PhysicalDimension.Height;
    
                    //Add a page that has the same size as the image
                    PdfPageBase page = doc.Pages.Add(new SizeF(width, height));
    
                    //Create a PdfImage object based on the image
                    PdfImage pdfImage = PdfImage.FromImage(image);
    
                    //Draw image at (0, 0) of the page
                    page.Canvas.DrawImage(pdfImage, 0, 0, pdfImage.Width, pdfImage.Height);
                }
    
                //Save to file
                doc.SaveToFile("CombinaImagesToPdf.pdf");
                doc.Dispose();
            }
        }
    }

C#/VB.NET: Convert Multiple Images into a Single PDF

Solicite una licencia temporal

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

Ver también

NuGet을 통해 설치됨

PM> Install-Package Spire.PDF

관련된 링크들

더 쉬운 배포 또는 저장을 위해 하나의 파일로 결합하려는 여러 이미지가 있는 경우 이를 단일 PDF 문서로 변환하는 것이 훌륭한 솔루션입니다. 이 프로세스는 공간을 절약할 뿐만 아니라 모든 이미지가 하나의 파일에 함께 보관되어 공유 또는 전송이 편리해집니다. 이 기사에서는 다음 방법을 배웁니다 Spire.PDF for .NET사용하여 C# 및 VB.NET에서 여러 이미지를 단일 PDF 문서로 결합합니다.

Spire.PDF for .NET 설치

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

PM> Install-Package Spire.PDF

C# 및 VB.NET에서 여러 이미지를 단일 PDF로 결합

폴더의 모든 이미지를 PDF로 변환하기 위해 각 이미지를 반복하고 이미지와 동일한 크기로 PDF에 새 페이지를 추가한 다음 새 페이지에 이미지를 그립니다. 자세한 단계는 다음과 같습니다.

  • PdfDocument 개체를 만듭니다.
  • PdfDocument.PageSettings.SetMargins() 메서드를 사용하여 페이지 여백을 0으로 설정합니다.
  • 이미지가 저장된 폴더를 가져옵니다.
  • 폴더의 각 이미지 파일을 반복하여 특정 이미지의 너비와 높이를 가져옵니다.
  • PdfDocument.Pages.Add() 메서드를 사용하여 이미지와 너비 및 높이가 동일한 새 페이지를 PDF 문서에 추가합니다.
  • PdfPageBase.Canvas.DrawImage() 메서드를 사용하여 페이지에 이미지를 그립니다.
  • PdfDocument.SaveToFile() 메서드를 사용하여 문서를 저장합니다.
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using System.Drawing;
    
    namespace ConvertMultipleImagesIntoPdf
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
    
                //Set the page margins to 0
                doc.PageSettings.SetMargins(0);
    
                //Get the folder where the images are stored
                DirectoryInfo folder = new DirectoryInfo(@"C:\Users\Administrator\Desktop\Images");
    
                //Iterate through the files in the folder
                foreach (FileInfo file in folder.GetFiles())
                {
                    //Load a particular image
                    Image image = Image.FromFile(file.FullName);
    
                    //Get the image width and height
                    float width = image.PhysicalDimension.Width;
                    float height = image.PhysicalDimension.Height;
    
                    //Add a page that has the same size as the image
                    PdfPageBase page = doc.Pages.Add(new SizeF(width, height));
    
                    //Create a PdfImage object based on the image
                    PdfImage pdfImage = PdfImage.FromImage(image);
    
                    //Draw image at (0, 0) of the page
                    page.Canvas.DrawImage(pdfImage, 0, 0, pdfImage.Width, pdfImage.Height);
                }
    
                //Save to file
                doc.SaveToFile("CombinaImagesToPdf.pdf");
                doc.Dispose();
            }
        }
    }

C#/VB.NET: Convert Multiple Images into a Single PDF

임시 라이센스 신청

생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.

또한보십시오

Installato tramite NuGet

PM> Install-Package Spire.PDF

Link correlati

Se disponi di più immagini che desideri combinare in un unico file per una distribuzione o un'archiviazione più semplice, convertirle in un unico documento PDF è un'ottima soluzione. Questo processo non solo consente di risparmiare spazio, ma garantisce anche che tutte le immagini siano conservate insieme in un unico file, rendendone conveniente la condivisione o il trasferimento. In questo articolo imparerai come farlo combinare diverse immagini in un unico documento PDF in C# e VB.NET utilizzando Spire.PDF for .NET.

Installa Spire.PDF for .NET

Per cominciare, devi aggiungere i file DLL inclusi nel pacchetto Spire.PDF for .NET come riferimenti nel tuo progetto .NET. I file DLL possono essere scaricati da questo link o installato tramite NuGet.

PM> Install-Package Spire.PDF

Combina più immagini in un unico PDF in C# e VB.NET

Per convertire tutte le immagini di una cartella in un PDF, iteriamo su ciascuna immagine, aggiungiamo una nuova pagina al PDF con le stesse dimensioni dell'immagine, quindi disegniamo l'immagine sulla nuova pagina. Di seguito sono riportati i passaggi dettagliati.

  • Crea un oggetto PdfDocument.
  • Imposta i margini della pagina su zero utilizzando il metodo PdfDocument.PageSettings.SetMargins().
  • Ottieni la cartella in cui sono archiviate le immagini.
  • Scorri ogni file immagine nella cartella e ottieni la larghezza e l'altezza di un'immagine specifica.
  • Aggiungi una nuova pagina che abbia la stessa larghezza e altezza dell'immagine al documento PDF utilizzando il metodo PdfDocument.Pages.Add().
  • Disegna l'immagine sulla pagina utilizzando il metodo PdfPageBase.Canvas.DrawImage().
  • Salvare il documento utilizzando il metodo PdfDocument.SaveToFile().
  • C#
  • VB.NET
using Spire.Pdf;
    using Spire.Pdf.Graphics;
    using System.Drawing;
    
    namespace ConvertMultipleImagesIntoPdf
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Create a PdfDocument object
                PdfDocument doc = new PdfDocument();
    
                //Set the page margins to 0
                doc.PageSettings.SetMargins(0);
    
                //Get the folder where the images are stored
                DirectoryInfo folder = new DirectoryInfo(@"C:\Users\Administrator\Desktop\Images");
    
                //Iterate through the files in the folder
                foreach (FileInfo file in folder.GetFiles())
                {
                    //Load a particular image
                    Image image = Image.FromFile(file.FullName);
    
                    //Get the image width and height
                    float width = image.PhysicalDimension.Width;
                    float height = image.PhysicalDimension.Height;
    
                    //Add a page that has the same size as the image
                    PdfPageBase page = doc.Pages.Add(new SizeF(width, height));
    
                    //Create a PdfImage object based on the image
                    PdfImage pdfImage = PdfImage.FromImage(image);
    
                    //Draw image at (0, 0) of the page
                    page.Canvas.DrawImage(pdfImage, 0, 0, pdfImage.Width, pdfImage.Height);
                }
    
                //Save to file
                doc.SaveToFile("CombinaImagesToPdf.pdf");
                doc.Dispose();
            }
        }
    }

C#/VB.NET: Convert Multiple Images into a Single PDF

Richiedi una licenza temporanea

Se desideri rimuovere il messaggio di valutazione dai documenti generati o eliminare le limitazioni della funzione, per favore richiedere una licenza di prova di 30 giorni per te.

Guarda anche