Как заменить изображения в PDF-документе с помощью C# и .NET


В этом примере кода показано, как найти все изображения в pdf-документе и заменить их на нужные.

Исходный pdf-документ, содержащий изображения:example.pdf

Загрузите полученный файл: replaced.pdf

Полный код

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SautinSoft.Document;
using SautinSoft.Document.Drawing;
using SautinSoft.Document.Tables;
using System.IO;
namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get your free 30-day key here:   
            // https://sautinsoft.com/start-for-free/

            ReplaceImagesInPdf();
        }

        /// <summary>
        /// How to replace images in PDF document.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/from-customers-replace-images-in-pdf-in-csharp-vb-net.php
        /// </remarks>
        static void ReplaceImagesInPdf()
        {

            // Path to a loadable document.
            string loadPath = @"..\..\..\example.pdf";
            string pictPath = @"..\..\..\replaceNA.jpg";

            // Load a document intoDocumentCore.
            DocumentCore dc = DocumentCore.Load(loadPath);
            
            // Load the Picture from a file.
            Picture picture = new Picture(dc, InlineLayout.Inline(new Size()), pictPath);
            
            // Find all pictures in the document.
            foreach (Element el in dc.GetChildElements(true, ElementType.Picture).Reverse())
            {
                if (el is Picture)
                {
                    // �opy all properties of the found picture and assign these properties to the new picture.
                    // If you do not do this, the picture may be inserted into an arbitrary place in the document. 
                    if (((Picture)el).Layout is FloatingLayout)
                    {
                        FloatingLayout old = (FloatingLayout )((Picture)el).Layout;
                        picture.Layout = FloatingLayout.Floating(old.HorizontalPosition, old.VerticalPosition, old.Size);
                    }

                    // Replace picture.
                    el.Content.Replace(picture.Content);
                }
            }

            // Save our document into PDF format.
            string savePath = @"replaced.pdf";
            dc.Save(savePath);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(loadPath) { UseShellExecute = true });
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(savePath) { UseShellExecute = true });
        }
    }
}

Download

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports SautinSoft.Document
Imports SautinSoft.Document.Drawing
Imports SautinSoft.Document.Tables
Imports System.IO
Namespace Example
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			ReplaceImagesInPdf()
		End Sub
                ''' Get your free 30-day key here:   
                ''' https://sautinsoft.com/start-for-free/
		''' <summary>
		''' How to replace images in PDF document.
		''' </summary>
		''' <remarks>
		''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/from-customers-replace-images-in-pdf-in-csharp-vb-net.php
		''' </remarks>
		Private Shared Sub ReplaceImagesInPdf()

			' Path to a loadable document.
			Dim loadPath As String = "..\..\..\example.pdf"
			Dim pictPath As String = "..\..\..\replaceNA.jpg"

			' Load a document intoDocumentCore.
			Dim dc As DocumentCore = DocumentCore.Load(loadPath)

			' Load the Picture from a file.
			Dim picture As New Picture(dc, InlineLayout.Inline(New Size()), pictPath)

			' Find all pictures in the document.
			For Each el As Element In dc.GetChildElements(True, ElementType.Picture).Reverse()
				If TypeOf el Is Picture Then
					' Сopy all properties of the found picture and assign these properties to the new picture.
					' If you do not do this, the picture may be inserted into an arbitrary place in the document. 
					If TypeOf (CType(el, Picture)).Layout Is FloatingLayout Then
						Dim old As FloatingLayout = CType(CType(el, Picture).Layout, FloatingLayout)
						picture.Layout = FloatingLayout.Floating(old.HorizontalPosition, old.VerticalPosition, old.Size)
					End If

					' Replace picture.
					el.Content.Replace(picture.Content)
				End If
			Next el

			' Save our document into PDF format.
			Dim savePath As String = "replaced.pdf"
			dc.Save(savePath)

			' Open the result for demonstration purposes.
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(loadPath) With {.UseShellExecute = True})
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(savePath) With {.UseShellExecute = True})
		End Sub
	End Class
End Namespace

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.