C#/VB.NET: вставка, замена или удаление изображений в PDF
Оглавление
Установлено через NuGet
PM> Install-Package Spire.PDF
Ссылки по теме
По сравнению с текстовыми документами документы, содержащие изображения, несомненно, более яркие и привлекательные для читателей. При создании или редактировании PDF-документа иногда может потребоваться вставить изображения, чтобы улучшить его внешний вид и сделать его более привлекательным. В этой статье вы узнаете, как вставлять, заменять или удалять изображения в документах PDF на C# и VB.NET. используя Spire.PDF for .NET.
- Вставка изображения в PDF-документ
- Замените изображение другим изображением в PDF-документе
- Удалить определенное изображение в PDF-документе
Установите Spire.PDF for .NET
Для начала вам необходимо добавить файлы DLL, включенные в пакет Spire.PDF for.NET, в качестве ссылок в ваш проект .NET. Файлы DLL можно загрузить по этой ссылке или установить через NuGet.
PM> Install-Package Spire.PDF
Вставка изображения в PDF-документ на C# и VB.NET
Следующие шаги демонстрируют, как вставить изображение в существующий PDF-документ:
- Инициализируйте экземпляр класса PdfDocument.
- Загрузите PDF-документ с помощью метода PdfDocument.LoadFromFile().
- Получите нужную страницу в PDF-документе через свойство PdfDocument.Pages[pageIndex].
- Загрузите изображение, используя метод PdfImage.FromFile().
- Укажите ширину и высоту области изображения на странице.
- Укажите координаты X и Y, чтобы начать рисовать изображение.
- Нарисуйте изображение на странице, используя метод PdfPageBase.Canvas.DrawImage().
- Сохраните полученный документ с помощью метода PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
namespace InsertImage
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Input.pdf");
//Get the first page in the PDF document
PdfPageBase page = pdf.Pages[0];
//Load an image
PdfImage image = PdfImage.FromFile("image.jpg");
//Specify the width and height of the image area on the page
float width = image.Width * 0.50f;
float height = image.Height * 0.50f;
//Specify the X and Y coordinates to start drawing the image
float x = 180f;
float y = 70f;
//Draw the image at a specified location on the page
page.Canvas.DrawImage(image, x, y, width, height);
//Save the result document
pdf.SaveToFile("AddImage.pdf", FileFormat.PDF);
}
}
}

Замена изображения другим изображением в PDF-документе на C# и VB.NET
Следующие шаги демонстрируют, как заменить изображение другим изображением в документе PDF:
- Инициализируйте экземпляр класса PdfDocument.
- Загрузите PDF-документ с помощью метода PdfDocument.LoadFromFile().
- Получите нужную страницу в PDF-документе через свойство PdfDocument.Pages[pageIndex].
- Загрузите изображение, используя метод PdfImage.FromFile().
- Инициализируйте экземпляр класса PdfImageHelper.
- Получите информацию об изображении со страницы, используя метод PdfImageHelper.GetImagesInfo().
- Замените определенное изображение на странице загруженным изображением с помощью метода PdfImageHelper.ReplaceImage().
- Сохраните полученный документ с помощью метода PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Utilities;
namespace ReplaceImage
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument instance
PdfDocument doc = new PdfDocument();
//Load a PDF document
doc.LoadFromFile("AddImage.pdf");
//Get the first page
PdfPageBase page = doc.Pages[0];
//Load an image
PdfImage image = PdfImage.FromFile("image1.jpg");
//Create a PdfImageHelper instance
PdfImageHelper imageHelper = new PdfImageHelper();
//Get the image information from the page
PdfImageInfo[] imageInfo = imageHelper.GetImagesInfo(page);
//Replace the first image on the page with the loaded image
imageHelper.ReplaceImage(imageInfo[0], image);
//Save the result document
doc.SaveToFile("ReplaceImage.pdf", FileFormat.PDF);
}
}
}

Удаление определенного изображения в PDF-документе на C# и VB.NET
Следующие шаги демонстрируют, как удалить изображение из документа PDF:
- Инициализируйте экземпляр класса PdfDocument.
- Загрузите PDF-документ с помощью метода PdfDocument.LoadFromFile().
- Получите нужную страницу в PDF-документе через свойство PdfDocument.Pages[pageIndex].
- Удалите определенное изображение на странице с помощью метода PdfPageBase.DeleteImage().
- Сохраните полученный документ с помощью метода PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
namespace DeleteImage
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
//Load a PDF document
pdf.LoadFromFile("AddImage.pdf");
//Get the first page
PdfPageBase page = pdf.Pages[0];
//Delete the first image on the page
page.DeleteImage(0);
//Save the result document
pdf.SaveToFile("DeleteImage.pdf", FileFormat.PDF);
}
}
}

Подать заявку на временную лицензию
Если вы хотите удалить сообщение об оценке из сгенерированных документов или избавиться от ограничений функции, пожалуйста запросите 30-дневную пробную лицензию для себя.
C#/VB.NET: Bilder in PDF einfügen, ersetzen oder löschen
Inhaltsverzeichnis
Über NuGet installiert
PM> Install-Package Spire.PDF
verwandte Links
Im Vergleich zu reinen Textdokumenten sind Dokumente mit Bildern zweifellos lebendiger und ansprechender für den Leser. Beim Erstellen oder Bearbeiten eines PDF-Dokuments müssen Sie möglicherweise manchmal Bilder einfügen, um das Erscheinungsbild zu verbessern und es ansprechender zu gestalten. In diesem Artikel erfahren Sie, wie das geht Einfügen, Ersetzen oder Löschen von Bildern in PDF-Dokumenten in C# und VB.NET Verwendung von Spire.PDF for .NET.
- Fügen Sie ein Bild in ein PDF-Dokument ein
- Ersetzen Sie ein Bild durch ein anderes Bild in einem PDF-Dokument
- Löschen Sie ein bestimmtes Bild in einem PDF-Dokument
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
Fügen Sie ein Bild in ein PDF-Dokument in C# und VB.NET ein
Die folgenden Schritte zeigen, wie Sie ein Bild in ein vorhandenes PDF-Dokument einfügen:
- Initialisieren Sie eine Instanz der PdfDocument-Klasse.
- Laden Sie ein PDF-Dokument mit der Methode PdfDocument.LoadFromFile().
- Rufen Sie die gewünschte Seite im PDF-Dokument über die Eigenschaft PdfDocument.Pages[pageIndex] ab.
- Laden Sie ein Bild mit der Methode PdfImage.FromFile().
- Geben Sie die Breite und Höhe des Bildbereichs auf der Seite an.
- Geben Sie die X- und Y-Koordinaten an, um mit dem Zeichnen des Bildes zu beginnen.
- Zeichnen Sie das Bild mit der Methode PdfPageBase.Canvas.DrawImage() auf die Seite.
- Speichern Sie das Ergebnisdokument mit der Methode PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
namespace InsertImage
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Input.pdf");
//Get the first page in the PDF document
PdfPageBase page = pdf.Pages[0];
//Load an image
PdfImage image = PdfImage.FromFile("image.jpg");
//Specify the width and height of the image area on the page
float width = image.Width * 0.50f;
float height = image.Height * 0.50f;
//Specify the X and Y coordinates to start drawing the image
float x = 180f;
float y = 70f;
//Draw the image at a specified location on the page
page.Canvas.DrawImage(image, x, y, width, height);
//Save the result document
pdf.SaveToFile("AddImage.pdf", FileFormat.PDF);
}
}
}

Ersetzen Sie ein Bild durch ein anderes Bild in einem PDF-Dokument in C# und VB.NET
Die folgenden Schritte zeigen, wie Sie ein Bild durch ein anderes Bild in einem PDF-Dokument ersetzen:
- Initialisieren Sie eine Instanz der PdfDocument-Klasse.
- Laden Sie ein PDF-Dokument mit der Methode PdfDocument.LoadFromFile().
- Rufen Sie die gewünschte Seite im PDF-Dokument über die Eigenschaft PdfDocument.Pages[pageIndex] ab.
- Laden Sie ein Bild mit der Methode PdfImage.FromFile().
- Initialisieren Sie eine Instanz der PdfImageHelper-Klasse.
- Rufen Sie die Bildinformationen von der Seite mit der Methode PdfImageHelper.GetImagesInfo() ab.
- Ersetzen Sie ein bestimmtes Bild auf der Seite durch das geladene Bild mit der Methode PdfImageHelper.ReplaceImage().
- Speichern Sie das Ergebnisdokument mit der Methode PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Utilities;
namespace ReplaceImage
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument instance
PdfDocument doc = new PdfDocument();
//Load a PDF document
doc.LoadFromFile("AddImage.pdf");
//Get the first page
PdfPageBase page = doc.Pages[0];
//Load an image
PdfImage image = PdfImage.FromFile("image1.jpg");
//Create a PdfImageHelper instance
PdfImageHelper imageHelper = new PdfImageHelper();
//Get the image information from the page
PdfImageInfo[] imageInfo = imageHelper.GetImagesInfo(page);
//Replace the first image on the page with the loaded image
imageHelper.ReplaceImage(imageInfo[0], image);
//Save the result document
doc.SaveToFile("ReplaceImage.pdf", FileFormat.PDF);
}
}
}

Löschen Sie ein bestimmtes Bild in einem PDF-Dokument in C# und VB.NET
Die folgenden Schritte zeigen, wie Sie ein Bild aus einem PDF-Dokument löschen:
- Initialisieren Sie eine Instanz der PdfDocument-Klasse.
- Laden Sie ein PDF-Dokument mit der Methode PdfDocument.LoadFromFile().
- Rufen Sie die gewünschte Seite im PDF-Dokument über die Eigenschaft PdfDocument.Pages[pageIndex] ab.
- Löschen Sie ein bestimmtes Bild auf der Seite mit der Methode PdfPageBase.DeleteImage().
- Speichern Sie das Ergebnisdokument mit der Methode PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
namespace DeleteImage
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
//Load a PDF document
pdf.LoadFromFile("AddImage.pdf");
//Get the first page
PdfPageBase page = pdf.Pages[0];
//Delete the first image on the page
page.DeleteImage(0);
//Save the result document
pdf.SaveToFile("DeleteImage.pdf", FileFormat.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.
C#/VB.NET: insertar, reemplazar o eliminar imágenes en PDF
Tabla de contenido
Instalado a través de NuGet
PM> Install-Package Spire.PDF
enlaces relacionados
En comparación con los documentos que sólo contienen texto, los documentos que contienen imágenes son sin duda más vívidos y atractivos para los lectores. Al generar o editar un documento PDF, es posible que en ocasiones necesites insertar imágenes para mejorar su apariencia y hacerlo más atractivo. En este artículo, aprenderá cómo insertar, reemplazar o eliminar imágenes en documentos PDF en C# y VB.NET usando Spire.PDF for .NET.
- Insertar una imagen en un documento PDF
- Reemplazar una imagen con otra imagen en un documento PDF
- Eliminar una imagen específica en un documento PDF
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
Insertar una imagen en un documento PDF en C# y VB.NET
Los siguientes pasos demuestran cómo insertar una imagen en un documento PDF existente:
- Inicialice una instancia de la clase PdfDocument.
- Cargue un documento PDF utilizando el método PdfDocument.LoadFromFile().
- Obtenga la página deseada en el documento PDF a través de la propiedad PdfDocument.Pages[pageIndex].
- Cargue una imagen usando el método PdfImage.FromFile().
- Especifique el ancho y el alto del área de la imagen en la página.
- Especifique las coordenadas X e Y para comenzar a dibujar la imagen.
- Dibuja la imagen en la página usando el método PdfPageBase.Canvas.DrawImage().
- Guarde el documento resultante utilizando el método PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
namespace InsertImage
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Input.pdf");
//Get the first page in the PDF document
PdfPageBase page = pdf.Pages[0];
//Load an image
PdfImage image = PdfImage.FromFile("image.jpg");
//Specify the width and height of the image area on the page
float width = image.Width * 0.50f;
float height = image.Height * 0.50f;
//Specify the X and Y coordinates to start drawing the image
float x = 180f;
float y = 70f;
//Draw the image at a specified location on the page
page.Canvas.DrawImage(image, x, y, width, height);
//Save the result document
pdf.SaveToFile("AddImage.pdf", FileFormat.PDF);
}
}
}

Reemplazar una imagen con otra imagen en un documento PDF en C# y VB.NET
Los siguientes pasos demuestran cómo reemplazar una imagen con otra imagen en un documento PDF:
- Inicialice una instancia de la clase PdfDocument.
- Cargue un documento PDF utilizando el método PdfDocument.LoadFromFile().
- Obtenga la página deseada en el documento PDF a través de la propiedad PdfDocument.Pages[pageIndex].
- Cargue una imagen usando el método PdfImage.FromFile().
- Inicialice una instancia de la clase PdfImageHelper.
- Obtenga la información de la imagen de la página utilizando el método PdfImageHelper.GetImagesInfo().
- Reemplace una imagen específica en la página con la imagen cargada usando el método PdfImageHelper.ReplaceImage().
- Guarde el documento resultante utilizando el método PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Utilities;
namespace ReplaceImage
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument instance
PdfDocument doc = new PdfDocument();
//Load a PDF document
doc.LoadFromFile("AddImage.pdf");
//Get the first page
PdfPageBase page = doc.Pages[0];
//Load an image
PdfImage image = PdfImage.FromFile("image1.jpg");
//Create a PdfImageHelper instance
PdfImageHelper imageHelper = new PdfImageHelper();
//Get the image information from the page
PdfImageInfo[] imageInfo = imageHelper.GetImagesInfo(page);
//Replace the first image on the page with the loaded image
imageHelper.ReplaceImage(imageInfo[0], image);
//Save the result document
doc.SaveToFile("ReplaceImage.pdf", FileFormat.PDF);
}
}
}

Eliminar una imagen específica en un documento PDF en C# y VB.NET
Los siguientes pasos demuestran cómo eliminar una imagen de un documento PDF:
- Inicialice una instancia de la clase PdfDocument.
- Cargue un documento PDF utilizando el método PdfDocument.LoadFromFile().
- Obtenga la página deseada en el documento PDF a través de la propiedad PdfDocument.Pages[pageIndex].
- Elimine una imagen específica en la página usando el método PdfPageBase.DeleteImage().
- Guarde el documento resultante utilizando el método PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
namespace DeleteImage
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
//Load a PDF document
pdf.LoadFromFile("AddImage.pdf");
//Get the first page
PdfPageBase page = pdf.Pages[0];
//Delete the first image on the page
page.DeleteImage(0);
//Save the result document
pdf.SaveToFile("DeleteImage.pdf", FileFormat.PDF);
}
}
}

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, por favor solicitar una licencia de prueba de 30 días para ti.
C#/VB.NET: PDF에서 이미지 삽입, 교체 또는 삭제
NuGet을 통해 설치됨
PM> Install-Package Spire.PDF
관련된 링크들
텍스트만 있는 문서에 비해 이미지가 포함된 문서는 의심할 여지 없이 더 생생하고 독자의 관심을 끌게 됩니다. PDF 문서를 생성하거나 편집할 때 모양을 개선하고 더욱 매력적으로 만들기 위해 이미지를 삽입해야 하는 경우가 있습니다. 이 기사에서는 다음 방법을 배웁니다 C# 및 VB.NET의 PDF 문서에서 이미지 삽입, 교체 또는 삭제 Spire.PDF for .NET사용합니다
Spire.PDF for .NET 설치
먼저 Spire.PDF for.NET 패키지에 포함된 DLL 파일을 .NET 프로젝트의 참조로 추가해야 합니다. DLL 파일은 이 링크 에서 다운로드하거나 NuGet을 통해 설치할 수 있습니다.
PM> Install-Package Spire.PDF
C# 및 VB.NET에서 PDF 문서에 이미지 삽입
다음 단계에서는 기존 PDF 문서에 이미지를 삽입하는 방법을 보여줍니다.
- PdfDocument 클래스의 인스턴스를 초기화합니다.
- PdfDocument.LoadFromFile() 메서드를 사용하여 PDF 문서를 로드합니다.
- PdfDocument.Pages[pageIndex] 속성을 통해 PDF 문서에서 원하는 페이지를 가져옵니다.
- PdfImage.FromFile() 메서드를 사용하여 이미지를 로드합니다.
- 페이지에서 이미지 영역의 너비와 높이를 지정합니다.
- 이미지 그리기를 시작하려면 X 및 Y 좌표를 지정하세요.
- PdfPageBase.Canvas.DrawImage() 메서드를 사용하여 페이지에 이미지를 그립니다.
- PdfDocument.SaveToFile() 메서드를 사용하여 결과 문서를 저장합니다.
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
namespace InsertImage
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Input.pdf");
//Get the first page in the PDF document
PdfPageBase page = pdf.Pages[0];
//Load an image
PdfImage image = PdfImage.FromFile("image.jpg");
//Specify the width and height of the image area on the page
float width = image.Width * 0.50f;
float height = image.Height * 0.50f;
//Specify the X and Y coordinates to start drawing the image
float x = 180f;
float y = 70f;
//Draw the image at a specified location on the page
page.Canvas.DrawImage(image, x, y, width, height);
//Save the result document
pdf.SaveToFile("AddImage.pdf", FileFormat.PDF);
}
}
}

C# 및 VB.NET의 PDF 문서에서 이미지를 다른 이미지로 바꾸기
다음 단계에서는 PDF 문서의 이미지를 다른 이미지로 바꾸는 방법을 보여줍니다.
- PdfDocument 클래스의 인스턴스를 초기화합니다.
- PdfDocument.LoadFromFile() 메서드를 사용하여 PDF 문서를 로드합니다.
- PdfDocument.Pages[pageIndex] 속성을 통해 PDF 문서에서 원하는 페이지를 가져옵니다.
- PdfImage.FromFile() 메서드를 사용하여 이미지를 로드합니다.
- PdfImageHelper 클래스의 인스턴스를 초기화합니다.
- PdfImageHelper.GetImagesInfo() 메서드를 사용하여 페이지에서 이미지 정보를 가져옵니다.
- PdfImageHelper.ReplaceImage() 메서드를 사용하여 페이지의 특정 이미지를 로드된 이미지로 바꿉니다.
- PdfDocument.SaveToFile() 메서드를 사용하여 결과 문서를 저장합니다.
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Utilities;
namespace ReplaceImage
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument instance
PdfDocument doc = new PdfDocument();
//Load a PDF document
doc.LoadFromFile("AddImage.pdf");
//Get the first page
PdfPageBase page = doc.Pages[0];
//Load an image
PdfImage image = PdfImage.FromFile("image1.jpg");
//Create a PdfImageHelper instance
PdfImageHelper imageHelper = new PdfImageHelper();
//Get the image information from the page
PdfImageInfo[] imageInfo = imageHelper.GetImagesInfo(page);
//Replace the first image on the page with the loaded image
imageHelper.ReplaceImage(imageInfo[0], image);
//Save the result document
doc.SaveToFile("ReplaceImage.pdf", FileFormat.PDF);
}
}
}

C# 및 VB.NET의 PDF 문서에서 특정 이미지 삭제
다음 단계에서는 PDF 문서에서 이미지를 삭제하는 방법을 보여줍니다.
- PdfDocument 클래스의 인스턴스를 초기화합니다.
- PdfDocument.LoadFromFile() 메서드를 사용하여 PDF 문서를 로드합니다.
- PdfDocument.Pages[pageIndex] 속성을 통해 PDF 문서에서 원하는 페이지를 가져옵니다.
- PdfPageBase.DeleteImage() 메서드를 사용하여 페이지의 특정 이미지를 삭제합니다.
- PdfDocument.SaveToFile() 메서드를 사용하여 결과 문서를 저장합니다.
- C#
- VB.NET
using Spire.Pdf;
namespace DeleteImage
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
//Load a PDF document
pdf.LoadFromFile("AddImage.pdf");
//Get the first page
PdfPageBase page = pdf.Pages[0];
//Delete the first image on the page
page.DeleteImage(0);
//Save the result document
pdf.SaveToFile("DeleteImage.pdf", FileFormat.PDF);
}
}
}

임시 라이센스 신청
생성된 문서에서 평가 메시지를 제거하고 싶거나, 기능 제한을 없애고 싶다면 30일 평가판 라이센스 요청 자신을 위해.
C#/VB.NET: inserisci, sostituisci o elimina immagini in PDF
Sommario
Installato tramite NuGet
PM> Install-Package Spire.PDF
Link correlati
Rispetto ai documenti di solo testo, i documenti contenenti immagini sono senza dubbio più vividi e coinvolgenti per i lettori. Quando generi o modifichi un documento PDF, a volte potrebbe essere necessario inserire immagini per migliorarne l'aspetto e renderlo più accattivante. In questo articolo imparerai come inserire, sostituire o eliminare immagini nei documenti PDF in C# e VB.NET utilizzando Spire.PDF for .NET.
- Inserisci un'immagine in un documento PDF
- Sostituisci un'immagine con un'altra immagine in un documento PDF
- Elimina un'immagine specifica in un documento PDF
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
Inserisci un'immagine in un documento PDF in C# e VB.NET
I seguenti passaggi mostrano come inserire un'immagine in un documento PDF esistente:
- Inizializza un'istanza della classe PdfDocument.
- Carica un documento PDF utilizzando il metodo PdfDocument.LoadFromFile().
- Ottieni la pagina desiderata nel documento PDF tramite la proprietà PdfDocument.Pages[pageIndex].
- Carica un'immagine utilizzando il metodo PdfImage.FromFile().
- Specificare la larghezza e l'altezza dell'area dell'immagine sulla pagina.
- Specificare le coordinate X e Y per iniziare a disegnare l'immagine.
- Disegna l'immagine sulla pagina utilizzando il metodo PdfPageBase.Canvas.DrawImage().
- Salvare il documento risultante utilizzando il metodo PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
namespace InsertImage
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Input.pdf");
//Get the first page in the PDF document
PdfPageBase page = pdf.Pages[0];
//Load an image
PdfImage image = PdfImage.FromFile("image.jpg");
//Specify the width and height of the image area on the page
float width = image.Width * 0.50f;
float height = image.Height * 0.50f;
//Specify the X and Y coordinates to start drawing the image
float x = 180f;
float y = 70f;
//Draw the image at a specified location on the page
page.Canvas.DrawImage(image, x, y, width, height);
//Save the result document
pdf.SaveToFile("AddImage.pdf", FileFormat.PDF);
}
}
}

Sostituisci un'immagine con un'altra immagine in un documento PDF in C# e VB.NET
I seguenti passaggi dimostrano come sostituire un'immagine con un'altra immagine in un documento PDF:
- Inizializza un'istanza della classe PdfDocument.
- Carica un documento PDF utilizzando il metodo PdfDocument.LoadFromFile().
- Ottieni la pagina desiderata nel documento PDF tramite la proprietà PdfDocument.Pages[pageIndex].
- Carica un'immagine utilizzando il metodo PdfImage.FromFile().
- Inizializza un'istanza della classe PdfImageHelper.
- Ottieni le informazioni sull'immagine dalla pagina utilizzando il metodo PdfImageHelper.GetImagesInfo().
- Sostituisci un'immagine specifica sulla pagina con l'immagine caricata utilizzando il metodo PdfImageHelper.ReplaceImage().
- Salvare il documento risultante utilizzando il metodo PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Utilities;
namespace ReplaceImage
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument instance
PdfDocument doc = new PdfDocument();
//Load a PDF document
doc.LoadFromFile("AddImage.pdf");
//Get the first page
PdfPageBase page = doc.Pages[0];
//Load an image
PdfImage image = PdfImage.FromFile("image1.jpg");
//Create a PdfImageHelper instance
PdfImageHelper imageHelper = new PdfImageHelper();
//Get the image information from the page
PdfImageInfo[] imageInfo = imageHelper.GetImagesInfo(page);
//Replace the first image on the page with the loaded image
imageHelper.ReplaceImage(imageInfo[0], image);
//Save the result document
doc.SaveToFile("ReplaceImage.pdf", FileFormat.PDF);
}
}
}

Elimina un'immagine specifica in un documento PDF in C# e VB.NET
I seguenti passaggi mostrano come eliminare un'immagine da un documento PDF:
- Inizializza un'istanza della classe PdfDocument.
- Carica un documento PDF utilizzando il metodo PdfDocument.LoadFromFile().
- Ottieni la pagina desiderata nel documento PDF tramite la proprietà PdfDocument.Pages[pageIndex].
- Elimina un'immagine specifica sulla pagina utilizzando il metodo PdfPageBase.DeleteImage().
- Salvare il documento risultante utilizzando il metodo PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
namespace DeleteImage
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
//Load a PDF document
pdf.LoadFromFile("AddImage.pdf");
//Get the first page
PdfPageBase page = pdf.Pages[0];
//Delete the first image on the page
page.DeleteImage(0);
//Save the result document
pdf.SaveToFile("DeleteImage.pdf", FileFormat.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.
C#/VB.NET : insérer, remplacer ou supprimer des images dans un PDF
Table des matières
Installé via NuGet
PM> Install-Package Spire.PDF
Liens connexes
Comparés aux documents contenant uniquement du texte, les documents contenant des images sont sans aucun doute plus vivants et plus attrayants pour les lecteurs. Lors de la génération ou de la modification d'un document PDF, vous devrez parfois insérer des images pour améliorer son apparence et le rendre plus attrayant. Dans cet article, vous apprendrez comment insérer, remplacer ou supprimer des images dans des documents PDF en C# et VB.NET en utilisant Spire.PDF for .NET.
- Insérer une image dans un document PDF
- Remplacer une image par une autre image dans un document PDF
- Supprimer une image spécifique dans un document PDF
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
Insérer une image dans un document PDF en C# et VB.NET
Les étapes suivantes montrent comment insérer une image dans un document PDF existant :
- Initialisez une instance de la classe PdfDocument.
- Chargez un document PDF à l'aide de la méthode PdfDocument.LoadFromFile().
- Obtenez la page souhaitée dans le document PDF via la propriété PdfDocument.Pages[pageIndex].
- Chargez une image à l’aide de la méthode PdfImage.FromFile().
- Spécifiez la largeur et la hauteur de la zone d'image sur la page.
- Spécifiez les coordonnées X et Y pour commencer à dessiner l'image.
- Dessinez l'image sur la page à l'aide de la méthode PdfPageBase.Canvas.DrawImage().
- Enregistrez le document résultat à l'aide de la méthode PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
namespace InsertImage
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Input.pdf");
//Get the first page in the PDF document
PdfPageBase page = pdf.Pages[0];
//Load an image
PdfImage image = PdfImage.FromFile("image.jpg");
//Specify the width and height of the image area on the page
float width = image.Width * 0.50f;
float height = image.Height * 0.50f;
//Specify the X and Y coordinates to start drawing the image
float x = 180f;
float y = 70f;
//Draw the image at a specified location on the page
page.Canvas.DrawImage(image, x, y, width, height);
//Save the result document
pdf.SaveToFile("AddImage.pdf", FileFormat.PDF);
}
}
}

Remplacer une image par une autre image dans un document PDF en C# et VB.NET
Les étapes suivantes montrent comment remplacer une image par une autre image dans un document PDF :
- Initialisez une instance de la classe PdfDocument.
- Chargez un document PDF à l'aide de la méthode PdfDocument.LoadFromFile().
- Obtenez la page souhaitée dans le document PDF via la propriété PdfDocument.Pages[pageIndex].
- Chargez une image à l’aide de la méthode PdfImage.FromFile().
- Initialisez une instance de la classe PdfImageHelper.
- Obtenez les informations sur l’image de la page à l’aide de la méthode PdfImageHelper.GetImagesInfo().
- Remplacez une image spécifique sur la page par l'image chargée à l'aide de la méthode PdfImageHelper.ReplaceImage().
- Enregistrez le document résultat à l'aide de la méthode PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Utilities;
namespace ReplaceImage
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument instance
PdfDocument doc = new PdfDocument();
//Load a PDF document
doc.LoadFromFile("AddImage.pdf");
//Get the first page
PdfPageBase page = doc.Pages[0];
//Load an image
PdfImage image = PdfImage.FromFile("image1.jpg");
//Create a PdfImageHelper instance
PdfImageHelper imageHelper = new PdfImageHelper();
//Get the image information from the page
PdfImageInfo[] imageInfo = imageHelper.GetImagesInfo(page);
//Replace the first image on the page with the loaded image
imageHelper.ReplaceImage(imageInfo[0], image);
//Save the result document
doc.SaveToFile("ReplaceImage.pdf", FileFormat.PDF);
}
}
}

Supprimer une image spécifique dans un document PDF en C# et VB.NET
Les étapes suivantes montrent comment supprimer une image d'un document PDF :
- Initialisez une instance de la classe PdfDocument.
- Chargez un document PDF à l'aide de la méthode PdfDocument.LoadFromFile().
- Obtenez la page souhaitée dans le document PDF via la propriété PdfDocument.Pages[pageIndex].
- Supprimez une image spécifique sur la page à l’aide de la méthode PdfPageBase.DeleteImage().
- Enregistrez le document résultat à l'aide de la méthode PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
namespace DeleteImage
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument instance
PdfDocument pdf = new PdfDocument();
//Load a PDF document
pdf.LoadFromFile("AddImage.pdf");
//Get the first page
PdfPageBase page = pdf.Pages[0];
//Delete the first image on the page
page.DeleteImage(0);
//Save the result document
pdf.SaveToFile("DeleteImage.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 fonctionnelles, veuillez demander une licence d'essai de 30 jours pour toi.
C#/VB.NET: Adicionar marcas d'água de imagem ao PDF
Instalado via NuGet
PM> Install-Package Spire.PDF
Links Relacionados
Uma marca d'água de imagem geralmente é um logotipo ou sinal que aparece no fundo de documentos digitais, indicando o proprietário dos direitos autorais do conteúdo. Colocar uma marca d'água em seu documento PDF com uma imagem pode impedir que seus dados sejam reutilizados ou modificados. Este artigo demonstra como adicione uma marca d'água de imagem a PDF em C# e VB.NET usando 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 DLLs podem ser baixados deste link ou instalados via NuGet.
- Package Manager
PM> Install-Package Spire.PDF
Adicionar uma marca d'água de imagem ao PDF
A seguir estão as principais etapas para adicionar uma marca d'água de imagem a um documento PDF.
- Crie um objeto PdfDocument e carregue um arquivo PDF de amostra usando o método PdfDocument.LoadFromFile().
- Carregue um arquivo de imagem usando o método Image.FromFile().
- Percorra as páginas do documento e obtenha a página específica por meio da propriedade PdfDocument.Pages[].
- Defina a imagem como plano de fundo/imagem de marca d'água da página atual por meio da propriedade PdfPageBase.BackgroundImage. Defina a posição e o tamanho da imagem por meio da propriedade PdfPageBase.BackgroundRegion.
- Salve o documento em um arquivo PDF diferente usando o método PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using System.Drawing;
namespace AddImageWatermark
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument document = new PdfDocument();
//Load a sample PDF document
document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf");
//Load an image
Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png");
//Get the image width and height
int imgWidth = image.Width;
int imgHeight = image.Height;
//Loop through the pages
for (int i = 0; i < document.Pages.Count; i++)
{
//Get the page width and height
float pageWidth = document.Pages[i].ActualSize.Width;
float pageHeight = document.Pages[i].ActualSize.Height;
//Set the background opacity
document.Pages[i].BackgroudOpacity = 0.3f;
//Set the background image of current page
document.Pages[i].BackgroundImage = image;
//Position the background image at the center of the page
Rectangle rect = new Rectangle((int)(pageWidth - imgWidth) / 2, (int)(pageHeight - imgHeight) / 2, imgWidth, imgHeight);
document.Pages[i].BackgroundRegion = rect;
}
//Save the document to file
document.SaveToFile("AddImageWatermark.pdf");
document.Close();
}
}
}
Imports Spire.Pdf
Imports System.Drawing
Namespace AddImageWatermark
Class Program
Shared Sub Main(ByVal args() As String)
'Create a PdfDocument object
Dim document As PdfDocument = New PdfDocument()
'Load a sample PDF document
document.LoadFromFile("C:\Users\Administrator\Desktop\sample.pdf")
'Load an image
Dim image As Image = Image.FromFile("C:\Users\Administrator\Desktop\logo.png")
'Get the image width and height
Dim imgWidth As Integer = image.Width
Dim imgHeight As Integer = image.Height
'Loop through the pages
Dim i As Integer
For i = 0 To document.Pages.Count- 1 Step i + 1
'Get the page width and height
Dim pageWidth As single = document.Pages(i).ActualSize.Width
Dim pageHeight As single = document.Pages(i).ActualSize.Height
'Set the background opacity
document.Pages(i).BackgroudOpacity = 0.3f
'Set the background image of current page
document.Pages(i).BackgroundImage = image
'Position the background image at the center of the page
Dim rect As Rectangle = New Rectangle(CType((pageWidth - imgWidth) / 2,(Integer)(pageHeight - imgHeight) / 2,imgWidth,imgHeight, Integer))
document.Pages(i).BackgroundRegion = rect
Next
'Save the document to file
document.SaveToFile("AddImageWatermark.pdf")
document.Close()
End Sub
End Class
End Namespace

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, por favor solicite uma licença de teste de 30 dias para você mesmo.
C#/VB.NET: добавление водяных знаков изображений в PDF
Установлено через 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.
- Package Manager
PM> Install-Package Spire.PDF
Добавить водяной знак изображения в PDF
Ниже приведены основные шаги по добавлению водяного знака изображения в документ PDF.
- Создайте объект PdfDocument и загрузите образец PDF-файла с помощью метода PdfDocument.LoadFromFile().
- Загрузите файл изображения с помощью метода Image.FromFile().
- Прокрутите страницы в документе и получите конкретную страницу через свойство PdfDocument.Pages[].
- Установите изображение в качестве фона/водяного знака текущей страницы через свойство PdfPageBase.BackgroundImage. Установите положение и размер изображения с помощью свойства PdfPageBase.BackgroundRegion.
- Сохраните документ в другой файл PDF с помощью метода PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using System.Drawing;
namespace AddImageWatermark
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument document = new PdfDocument();
//Load a sample PDF document
document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf");
//Load an image
Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png");
//Get the image width and height
int imgWidth = image.Width;
int imgHeight = image.Height;
//Loop through the pages
for (int i = 0; i < document.Pages.Count; i++)
{
//Get the page width and height
float pageWidth = document.Pages[i].ActualSize.Width;
float pageHeight = document.Pages[i].ActualSize.Height;
//Set the background opacity
document.Pages[i].BackgroudOpacity = 0.3f;
//Set the background image of current page
document.Pages[i].BackgroundImage = image;
//Position the background image at the center of the page
Rectangle rect = new Rectangle((int)(pageWidth - imgWidth) / 2, (int)(pageHeight - imgHeight) / 2, imgWidth, imgHeight);
document.Pages[i].BackgroundRegion = rect;
}
//Save the document to file
document.SaveToFile("AddImageWatermark.pdf");
document.Close();
}
}
}
Imports Spire.Pdf
Imports System.Drawing
Namespace AddImageWatermark
Class Program
Shared Sub Main(ByVal args() As String)
'Create a PdfDocument object
Dim document As PdfDocument = New PdfDocument()
'Load a sample PDF document
document.LoadFromFile("C:\Users\Administrator\Desktop\sample.pdf")
'Load an image
Dim image As Image = Image.FromFile("C:\Users\Administrator\Desktop\logo.png")
'Get the image width and height
Dim imgWidth As Integer = image.Width
Dim imgHeight As Integer = image.Height
'Loop through the pages
Dim i As Integer
For i = 0 To document.Pages.Count- 1 Step i + 1
'Get the page width and height
Dim pageWidth As single = document.Pages(i).ActualSize.Width
Dim pageHeight As single = document.Pages(i).ActualSize.Height
'Set the background opacity
document.Pages(i).BackgroudOpacity = 0.3f
'Set the background image of current page
document.Pages(i).BackgroundImage = image
'Position the background image at the center of the page
Dim rect As Rectangle = New Rectangle(CType((pageWidth - imgWidth) / 2,(Integer)(pageHeight - imgHeight) / 2,imgWidth,imgHeight, Integer))
document.Pages(i).BackgroundRegion = rect
Next
'Save the document to file
document.SaveToFile("AddImageWatermark.pdf")
document.Close()
End Sub
End Class
End Namespace

Подать заявку на временную лицензию
Если вы хотите удалить оценочное сообщение из сгенерированных документов или избавиться от функциональных ограничений, пожалуйста запросить 30-дневную пробную лицензию для себя.
C#/VB.NET: Bildwasserzeichen zu PDF hinzufügen
Inhaltsverzeichnis
Über NuGet installiert
PM> Install-Package Spire.PDF
verwandte Links
Ein Bildwasserzeichen ist normalerweise ein Logo oder Zeichen, das auf dem Hintergrund digitaler Dokumente erscheint und den Urheberrechtsinhaber des Inhalts angibt. Wenn Sie Ihr PDF-Dokument mit einem Bild mit einem Wasserzeichen versehen, können Sie verhindern, dass Ihre Daten wiederverwendet oder geändert werden. Dieser Artikel zeigt, wie es geht Fügen Sie dem PDF ein Bildwasserzeichen hinzu 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 DLLs-Dateien können entweder über diesen Link heruntergeladen oder über NuGet installiert werden.
- Package Manager
PM> Install-Package Spire.PDF
Fügen Sie ein Bildwasserzeichen zu PDF hinzu
Im Folgenden finden Sie die wichtigsten Schritte zum Hinzufügen eines Bildwasserzeichens zu einem PDF-Dokument.
- Erstellen Sie ein PdfDocument-Objekt und laden Sie eine Beispiel-PDF-Datei mit der Methode PdfDocument.LoadFromFile(). method.
- Laden Sie eine Bilddatei mit der Methode Image.FromFile().
- Durchlaufen Sie die Seiten im Dokument und rufen Sie die spezifische Seite über die Eigenschaft PdfDocument.Pages[] ab.
- Legen Sie das Bild über die Eigenschaft PdfPageBase.BackgroundImage als Hintergrund-/Wasserzeichenbild der aktuellen Seite fest. Legen Sie die Bildposition und -größe über die Eigenschaft PdfPageBase.BackgroundRegion fest.
- Speichern Sie das Dokument mit der Methode PdfDocument.SaveToFile() in einer anderen PDF-Datei.
- C#
- VB.NET
using Spire.Pdf;
using System.Drawing;
namespace AddImageWatermark
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument document = new PdfDocument();
//Load a sample PDF document
document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf");
//Load an image
Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png");
//Get the image width and height
int imgWidth = image.Width;
int imgHeight = image.Height;
//Loop through the pages
for (int i = 0; i < document.Pages.Count; i++)
{
//Get the page width and height
float pageWidth = document.Pages[i].ActualSize.Width;
float pageHeight = document.Pages[i].ActualSize.Height;
//Set the background opacity
document.Pages[i].BackgroudOpacity = 0.3f;
//Set the background image of current page
document.Pages[i].BackgroundImage = image;
//Position the background image at the center of the page
Rectangle rect = new Rectangle((int)(pageWidth - imgWidth) / 2, (int)(pageHeight - imgHeight) / 2, imgWidth, imgHeight);
document.Pages[i].BackgroundRegion = rect;
}
//Save the document to file
document.SaveToFile("AddImageWatermark.pdf");
document.Close();
}
}
}
Imports Spire.Pdf
Imports System.Drawing
Namespace AddImageWatermark
Class Program
Shared Sub Main(ByVal args() As String)
'Create a PdfDocument object
Dim document As PdfDocument = New PdfDocument()
'Load a sample PDF document
document.LoadFromFile("C:\Users\Administrator\Desktop\sample.pdf")
'Load an image
Dim image As Image = Image.FromFile("C:\Users\Administrator\Desktop\logo.png")
'Get the image width and height
Dim imgWidth As Integer = image.Width
Dim imgHeight As Integer = image.Height
'Loop through the pages
Dim i As Integer
For i = 0 To document.Pages.Count- 1 Step i + 1
'Get the page width and height
Dim pageWidth As single = document.Pages(i).ActualSize.Width
Dim pageHeight As single = document.Pages(i).ActualSize.Height
'Set the background opacity
document.Pages(i).BackgroudOpacity = 0.3f
'Set the background image of current page
document.Pages(i).BackgroundImage = image
'Position the background image at the center of the page
Dim rect As Rectangle = New Rectangle(CType((pageWidth - imgWidth) / 2,(Integer)(pageHeight - imgHeight) / 2,imgWidth,imgHeight, Integer))
document.Pages(i).BackgroundRegion = rect
Next
'Save the document to file
document.SaveToFile("AddImageWatermark.pdf")
document.Close()
End Sub
End Class
End Namespace

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.
C#/VB.NET: Agregar marcas de agua de imagen a PDF
Tabla de contenido
Instalado a través de NuGet
PM> Install-Package Spire.PDF
enlaces relacionados
Una marca de agua de imagen suele ser un logotipo o signo que aparece en el fondo de los documentos digitales, indicando el propietario de los derechos de autor del contenido. La marca de agua de su documento PDF con una imagen puede evitar que sus datos se reutilicen o modifiquen. Este artículo demuestra cómo agregue una marca de agua de imagen a 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.
- Package Manager
PM> Install-Package Spire.PDF
Agregar una marca de agua de imagen a PDF
Los siguientes son los pasos principales para agregar una marca de agua de imagen a un documento PDF.
- Cree un objeto PdfDocument y cargue un archivo PDF de muestra utilizando el método PdfDocument.LoadFromFile().
- Cargue un archivo de imagen usando el método Image.FromFile().
- Recorra las páginas del documento y obtenga la página específica a través de la propiedad PdfDocument.Pages[].
- Establezca la imagen como imagen de fondo/marca de agua de la página actual a través de la propiedad PdfPageBase.BackgroundImage. Establezca la posición y el tamaño de la imagen a través de la propiedad PdfPageBase.BackgroundRegion.
- Guarde el documento en un archivo PDF diferente usando el método PdfDocument.SaveToFile().
- C#
- VB.NET
using Spire.Pdf;
using System.Drawing;
namespace AddImageWatermark
{
class Program
{
static void Main(string[] args)
{
//Create a PdfDocument object
PdfDocument document = new PdfDocument();
//Load a sample PDF document
document.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf");
//Load an image
Image image = Image.FromFile(@"C:\Users\Administrator\Desktop\logo.png");
//Get the image width and height
int imgWidth = image.Width;
int imgHeight = image.Height;
//Loop through the pages
for (int i = 0; i < document.Pages.Count; i++)
{
//Get the page width and height
float pageWidth = document.Pages[i].ActualSize.Width;
float pageHeight = document.Pages[i].ActualSize.Height;
//Set the background opacity
document.Pages[i].BackgroudOpacity = 0.3f;
//Set the background image of current page
document.Pages[i].BackgroundImage = image;
//Position the background image at the center of the page
Rectangle rect = new Rectangle((int)(pageWidth - imgWidth) / 2, (int)(pageHeight - imgHeight) / 2, imgWidth, imgHeight);
document.Pages[i].BackgroundRegion = rect;
}
//Save the document to file
document.SaveToFile("AddImageWatermark.pdf");
document.Close();
}
}
}
Imports Spire.Pdf
Imports System.Drawing
Namespace AddImageWatermark
Class Program
Shared Sub Main(ByVal args() As String)
'Create a PdfDocument object
Dim document As PdfDocument = New PdfDocument()
'Load a sample PDF document
document.LoadFromFile("C:\Users\Administrator\Desktop\sample.pdf")
'Load an image
Dim image As Image = Image.FromFile("C:\Users\Administrator\Desktop\logo.png")
'Get the image width and height
Dim imgWidth As Integer = image.Width
Dim imgHeight As Integer = image.Height
'Loop through the pages
Dim i As Integer
For i = 0 To document.Pages.Count- 1 Step i + 1
'Get the page width and height
Dim pageWidth As single = document.Pages(i).ActualSize.Width
Dim pageHeight As single = document.Pages(i).ActualSize.Height
'Set the background opacity
document.Pages(i).BackgroudOpacity = 0.3f
'Set the background image of current page
document.Pages(i).BackgroundImage = image
'Position the background image at the center of the page
Dim rect As Rectangle = New Rectangle(CType((pageWidth - imgWidth) / 2,(Integer)(pageHeight - imgHeight) / 2,imgWidth,imgHeight, Integer))
document.Pages(i).BackgroundRegion = rect
Next
'Save the document to file
document.SaveToFile("AddImageWatermark.pdf")
document.Close()
End Sub
End Class
End Namespace

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, por favor solicitar una licencia de prueba de 30 días para ti.