Java — Добавление, скрытие или удаление слоев в PDF

Слой PDF — это интерактивная функция для PDF-документов. Слой можно рассматривать как отдельную наложенную страницу, на которую можно добавить текст, изображения или другие элементы. Слой может иметь имя, и пользователь может изменить, будет ли этот слой виден или нет. В этой статье показано, как добавлять, скрывать или удалять слои в PDF-документе с помощью Spire.PDF for Java.

  • Добавление слоев в PDF
  • Установка видимости слоев в PDF
  • Удаление слоев из PDF

Добавьте Spire.Pdf.jar в качестве зависимости

Если вы работаете над проектом maven, вы можете включить зависимость в файл pom.xml с помощью этой команды:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>8.7.0</version>
    </dependency>
</dependencies>
Вход в полноэкранный режим Выйти из полноэкранного режима

Если вы не используете maven, то вы можете найти необходимые jar-файлы из zip-файла, доступного в этом месте. Включите все jar-файлы в папку lib приложения, чтобы запустить пример кода, приведенный в этом руководстве.

Добавление слоев в PDF

Ниже описаны шаги по созданию слоев в PDF-документе с помощью Spire.PDF for Java.

  • Создайте объект PdfDocument и загрузите существующий PDF-файл.
  • Создайте объект PdfLayer с помощью метода Document.getLayers().addLayer(string layerName).
  • Создайте холст для слоя с помощью метода PdfLayer.createGraphics().
  • Нарисуйте текст, изображение или другие элементы на холсте.
  • Сохраните документ в другой PDF-файл с помощью метода PdfDocument.saveToFile().
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.*;
import com.spire.pdf.graphics.layer.PdfLayer;

import java.awt.*;
import java.awt.geom.Dimension2D;
import java.io.IOException;

public class AddLayersToPdf {

    public static void main(String[] args) throws IOException {

        //Create a PdfDocument object and load the sample PDF file
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("C:\Users\Administrator\Desktop\Terms of Service.pdf");
        //Invoke AddLayerWatermark method to add a watermark layer
        AddLayerWatermark(pdf);
        //Invoke AddLayerHeader method to add a header layer
        AddLayerHeader(pdf);
        //Save to file
        pdf.saveToFile("output/AddLayers.pdf");
        pdf.close();
    }

    private static void AddLayerWatermark(PdfDocument doc) throws IOException {

        //Create a layer named "watermark"
        PdfLayer layer = doc.getLayers().addLayer("watermark");
        //Create a font
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.PLAIN,48),true);
        //Specify watermark text
        String watermarkText = "CONFIDENTIAL";
        //Get text size
        Dimension2D fontSize = font.measureString(watermarkText);
        //Calculate two offsets
        float offset1 = (float)(fontSize.getWidth() * Math.sqrt(2) / 4);
        float offset2 = (float)(fontSize.getHeight() * Math.sqrt(2) / 4);
        //Get page count
        int pageCount = doc.getPages().getCount();
        //Declare two variables
        PdfPageBase page;
        PdfCanvas canvas;
        //Loop through the pages
        for (int i = 0; i < pageCount; i++) {

            page = doc.getPages().get(i);
            //Create a canvas from layer
            canvas = layer.createGraphics(page.getCanvas());
            canvas.translateTransform(canvas.getSize().getWidth() / 2 - offset1 - offset2, canvas.getSize().getHeight() / 2 + offset1 - offset2);
            canvas.setTransparency(0.4f);
            canvas.rotateTransform(-45);
            //Draw sting on the canvas of layer
            canvas.drawString(watermarkText, font, PdfBrushes.getDarkBlue(), 0, 0);
        }
    }

    private static void AddLayerHeader(PdfDocument doc) {

        //Create a layer named "header"
        PdfLayer layer = doc.getLayers().addLayer("header");
        //Get page size
        Dimension2D size = doc.getPages().get(0).getSize();
        //Specify the initial values of X and y
        float x = 70;
        float y = 15;
        //Get page count
        int pageCount = doc.getPages().getCount();
        //Declare two variables
        PdfPageBase page;
        PdfCanvas canvas;
        //Loop through the pages
        for (int i = 0; i < pageCount; i++) {

            //Draw an image on the layer
            PdfImage pdfImage = PdfImage.fromFile("C:\Users\Administrator\Desktop\terms.png");
            float width = pdfImage.getWidth();
            float height = pdfImage.getHeight();
            page = doc.getPages().get(i);
            canvas = layer.createGraphics(page.getCanvas());
            canvas.drawImage(pdfImage, x, y, width, height);
            //Draw a line on the layer
            PdfPen pen = new PdfPen(PdfBrushes.getDarkGray(), 2f);
            canvas.drawLine(pen, x, y + height + 5, size.getWidth() - x, y + height + 2);
        }
    }
}
Вход в полноэкранный режим Выход из полноэкранного режима

Установка видимости слоев в PDF

Ниже описаны шаги по установке видимости слоев в PDF с помощью Spire.PDF for Java.

  • Создайте объект PdfDocument и загрузите существующий PDF-файл, содержащий слои.
  • Получите определенный слой в PDF с помощью метода PdfDocument.getLayers().get(int index).
  • Установите видимость слоя с помощью метода **PdfLayer.setVisibility() **.
  • Сохраните документ в другой PDF-файл с помощью метода PdfDocument.saveToFile().
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.graphics.layer.PdfVisibility;

public class SetLayerVisibility {
    public static void main(String[] args) {

        //Create a PdfDocument object and load the sample PDF file
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("C:\Users\Administrator\Desktop\AddLayers.pdf");

        //Set the visibility of the first layer to off
        pdf.getLayers().get(0).setVisibility(PdfVisibility.Off);

        //Save to file
        pdf.saveToFile("output/HideLayer.pdf", FileFormat.PDF);
        pdf.dispose();
    }
}
Вход в полноэкранный режим Выход из полноэкранного режима

Удаление слоев из PDF

Ниже описаны шаги по удалению определенного слоя в PDF с помощью Spire.PDF for Java.

  • Создайте объект PdfDocument.
  • Загрузите PDF-файл, содержащий слои, используя метод PdfDocument.loadFromFile().
  • Получите коллекцию слоев из документа с помощью метода PdfDocument.getLayers().
  • Удалить определенный слой с помощью метода PdfLayerCollection.removeLayer().
  • Сохранить документ в другой файл с помощью метода PdfDocument.saveToFile().
import com.spire.pdf.PdfDocument;

public class DeleteLayers {

    public static void main(String[] args) {

        //Create a PdfDocument object and load the sample PDF file
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("C:\Users\Administrator\Desktop\AddLayers.pdf");

        //Delete the specific layer by its name
        pdf.getLayers().removeLayer("watermark");

        //Save to file
        pdf.saveToFile("output/DeleteLayer.pdf");
        pdf.close();
    }
}
Вход в полноэкранный режим Выход из полноэкранного режима

Оцените статью
devanswers.ru
Добавить комментарий