Вставьте изображение на пользовательскую страницу и разместите его в существующем документе DOCX с помощью C# и .NET

  1. Добавьте SautinSoft.Document из Nuget.
  2. Загрузите документ DOCX.
  3. Найдите нужный текст.
  4. Вставьте картинку после текста.

В этом примере мы вставим картинку на 1-е место после слова "Sign:".

Полный код

using System.Linq;
using System.IO;
using SautinSoft.Document;
using SautinSoft.Document.Drawing;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get your free 30-day key here:   
            // https://sautinsoft.com/start-for-free/

            InsertPictureToCustomPageAndPosition();
        }
        /// <summary>
        /// Insert a picture to custom page and position into existing DOCX document.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/insert-picture-jpg-image-to-custom-docx-page-and-position-net-csharp-vb.php
        /// </remarks>
        static void InsertPictureToCustomPageAndPosition()
        {
            // In this example we'll insert the picture to 1st after the word "Sign:".            

            string inpFile = @"..\..\..\example.docx";
            string outFile = @"Result.docx";
            string pictFile = @"..\..\..\picture.jpg";

            DocumentCore dc = DocumentCore.Load(inpFile);
            DocumentPaginator dp = dc.GetPaginator();

            // Find the text "Sign:" on the 1st page.
            ContentRange cr = dp.Pages[0].Content.Find("Sign:").LastOrDefault();
            if (cr != null)
            {
                Picture pic = new Picture(dc, pictFile);
                cr.End.Insert(pic.Content);
            }
            // Save the document as new DOCX and open it.
            dc.Save(outFile);
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });
        }
    }
}

Download

Imports System.Linq
Imports System.IO
Imports SautinSoft.Document
Imports SautinSoft.Document.Drawing

Namespace Example
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			InsertPictureToCustomPageAndPosition()
		End Sub
                ''' Get your free 30-day key here:   
                ''' https://sautinsoft.com/start-for-free/
		''' <summary>
		''' Insert a picture to custom page and position into existing DOCX document.
		''' </summary>
		''' <remarks>
		''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/insert-picture-jpg-image-to-custom-docx-page-and-position-net-csharp-vb.php
		''' </remarks>
		Private Shared Sub InsertPictureToCustomPageAndPosition()
			' In this example we'll insert the picture to 1st after the word "Sign:".            

			Dim inpFile As String = "..\..\..\example.docx"
			Dim outFile As String = "Result.docx"
			Dim pictFile As String = "..\..\..\picture.jpg"

			Dim dc As DocumentCore = DocumentCore.Load(inpFile)
			Dim dp As DocumentPaginator = dc.GetPaginator()

			' Find the text "Sign:" on the 1st page.
			Dim cr As ContentRange = dp.Pages(0).Content.Find("Sign:").LastOrDefault()
			If cr IsNot Nothing Then
				Dim pic As New Picture(dc, pictFile)
				cr.End.Insert(pic.Content)
			End If
			' Save the document as new DOCX and open it.
			dc.Save(outFile)
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(outFile) With {.UseShellExecute = True})
		End Sub
	End Class
End Namespace

Download


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



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

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