冰蓝科技
|
028-81705109
|
|
微信扫一扫
|

Spire.Cloud 纯前端文档控件

Spire. Office 5.12.8已正式发布。该版本带来了很多新的功能,比如:Spire.Doc 支持获取两个 Word 文档之间比较出的差异;Spire.XLS 支持调整弯箭头的折线位置;Spire.PDF 支持了添加页面标签,以及支持通过外部服务进行数字签名并且支持设置PDF包中文件的字段并对文件进行排序等等。同时,该版本修复了大量问题。详情请阅读以下内容。

该版本涵盖了最新版的Spire.Doc, Spire.PDF, Spire.XLS, Spire.Presentation, Spire.Email, Spire.DocViewer, Spire.PDFViewer, Spire.Spreadsheet, Spire.OfficeViewer, Spire.DataExport, Spire.Barcode。

版本信息如下:

获取Spire.Office 5.12.8, 请点击:

https://www.e-iceblue.cn/Downloads/Spire-Office-NET.html


Spire.Doc

新功能:

问题修复:


Spire.XLS

新功能:

问题修复:


Spire.Spreadsheet

问题修复:


Spire.PDF

优化:

新功能:

问题修复:

人们常常需要出于各种原因替换 PDF 文档中的文本。这可能是为了纠正错误或打字错误,更新过时的信息,为特定的受众个性化定制内容,或者为符合法律或监管变化要求。通过在 PDF 中替换文本,可以保持文档的完整性,并提高所呈现信息的整体质量和相关性。在本文中,你将学习如何使用 Spire.PDF for Java 在 PDF 文档中查找替换文本。

安装 Spire.PDF for Java

首先,您需要在 Java 程序中添加 Spire.Pdf.jar 文件作为依赖项。JAR 文件可以从此链接下载。 如果您使用 Maven,则可以将以下代码添加到项目的 pom.xml 文件中,从而轻松地在应用程序中导入 JAR 文件

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>12.9.0</version>
    </dependency>
</dependencies>

替换特定 PDF 页面的文本

在 Spire.PDF for Java 中,PdfTextReplacer 类用于 PDF 文档中的文本替换操作。它的主要方法之一 replaceAllText(),支持将 PDF 页面上指定文本替换为新的文本。具体步骤如下:

  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.texts.PdfTextReplaceOptions;
import com.spire.pdf.texts.PdfTextReplacer;
import com.spire.pdf.texts.ReplaceActionType;
import java.util.EnumSet;

public class ReplaceTextInPage
{

    public static void main(String[] args)
    {

        // 创建一个PdfDocument对象
        PdfDocument doc = new PdfDocument();

        // 加载一个PDF文件
        doc.loadFromFile("in.pdf");

        // 创建一个PdfTextReplaceOptions对象
        PdfTextReplaceOptions textReplaceOptions = new PdfTextReplaceOptions();

        // 指定文本替换的选项
        textReplaceOptions.setReplaceType(EnumSet.of(ReplaceActionType.IgnoreCase));
        textReplaceOptions.setReplaceType(EnumSet.of(ReplaceActionType.WholeWord));

        // 获取特定的页面
        PdfPageBase page = doc.getPages().get(0);

        // 根据页面创建一个PdfTextReplacer对象
        PdfTextReplacer textReplacer = new PdfTextReplacer(page);

        // 设置替换选项
        textReplacer.setOptions(textReplaceOptions);

        // 将所有目标文本实例替换为新文本
        textReplacer.replaceAllText("荷塘", "池塘");

        // 将文档保存到不同的PDF文件
        doc.saveToFile("out.pdf");

        // 释放资源
        doc.dispose();
    }
}

替换整个 PDF 文档匹配的文本

上面介绍了如何在单页中替换文本。要在整个 PDF 文档中将所有特定文本替换为新文本,只需遍历文档的每一页,具体实现如下:

  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.texts.PdfTextReplaceOptions;
import com.spire.pdf.texts.PdfTextReplacer;
import com.spire.pdf.texts.ReplaceActionType;
import java.util.EnumSet;

public class ReplaceTextInDocument 
{

     public static void main(String[] args) 
     {
    // 创建一个PdfDocument对象
    PdfDocument doc = new PdfDocument();

    // 加载一个PDF文件
    doc.loadFromFile("in.pdf");

    // 创建一个PdfTextReplaceOptions对象
    PdfTextReplaceOptions textReplaceOptions = new PdfTextReplaceOptions();

    // 指定文本替换的选项
    textReplaceOptions.setReplaceType(EnumSet.of(ReplaceActionType.IgnoreCase));
    textReplaceOptions.setReplaceType(EnumSet.of(ReplaceActionType.WholeWord));

    //遍历PDF文档所有页面
    for (int i = 0; i < doc.getPages().getCount(); i++)
        {
            PdfPageBase page = doc.getPages().get(i);

      // 根据页面创建一个PdfTextReplacer对象
      PdfTextReplacer textReplacer = new PdfTextReplacer(page);

      // 设置替换选项
      textReplacer.setOptions(textReplaceOptions);

      // 将所有目标文本实例替换为新文本
      textReplacer.replaceAllText("荷塘", "池塘");
        }

    // 将文档保存到不同的PDF文件
    doc.saveToFile("out.pdf");

    // 释放资源
    doc.dispose();
    }
}

Java 在 PDF 中查找替换文本

替换第一个匹配的文本

在 Java 中替换 PDF 第一个匹配的目标文本,使用 PdfTextReplacer 类的 replaceText() 方法。具体参考以下步骤:

  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.texts.PdfTextReplaceOptions;
import com.spire.pdf.texts.PdfTextReplacer;
import com.spire.pdf.texts.ReplaceActionType;
import java.util.EnumSet;

public class ReplaceFirstInstance {

    public static void main(String[] args)
    {

    // 创建一个PdfDocument对象
    PdfDocument doc = new PdfDocument();

    // 加载一个PDF文件
    doc.loadFromFile("in.pdf");

    // 创建一个PdfTextReplaceOptions对象
    PdfTextReplaceOptions textReplaceOptions = new PdfTextReplaceOptions();

    // 指定文本替换的选项
    textReplaceOptions.setReplaceType(EnumSet.of(ReplaceActionType.IgnoreCase));
        textReplaceOptions.setReplaceType(EnumSet.of(ReplaceActionType.WholeWord));

    // 获取特定页面
    PdfPageBase page = doc.getPages().get(0);

    // 根据页面创建一个PdfTextReplacer对象
    PdfTextReplacer textReplacer = new PdfTextReplacer(page);

    // 设置替换选项
    textReplacer.setOptions(textReplaceOptions);

        // 将目标文本的第一个实例替换为新文本
    textReplacer.replaceText("荷塘", "池塘");

    // 将文档保存到不同的PDF文件
    doc.saveToFile("out.pdf");

    // 释放资源
    doc.dispose();
    }
}

Java 在 PDF 中查找替换文本

基于正则表达式替换文本

正则表达式是一种非常强大和灵活的模式,通常用于匹配文本。在 Spire.PDF for Java 中,同样可以利用正则表达式在 PDF 文档页面中匹配特定文本并替换为新文本,步骤如下:

  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.texts.PdfTextReplaceOptions;
import com.spire.pdf.texts.PdfTextReplacer;
import com.spire.pdf.texts.ReplaceActionType;
import java.util.EnumSet;

public class ReplaceBasedOnRegularExpression {

    public static void main(String[] args) {

    // 创建一个PdfDocument对象
    PdfDocument doc = new PdfDocument();

    // 加载一个PDF文件
    doc.loadFromFile("in.pdf");

    // 创建一个PdfTextReplaceOptions对象
    PdfTextReplaceOptions textReplaceOptions = new PdfTextReplaceOptions();

        // 将替换类型设置为Regex
        textReplaceOptions.setReplaceType(EnumSet.of(ReplaceActionType.Regex));

    // 获取特定页面
    PdfPageBase page = doc.getPages().get(0);

    // 根据页面创建一个PdfTextReplacer对象
    PdfTextReplacer textReplacer = new PdfTextReplacer(page);

    // 设置替换选项
    textReplacer.setOptions(textReplaceOptions);

    // 指定正则表达式
    String regularExpression = "荷.月";

    // 将所有匹配正则表达式的目标文本替换为新文本
    textReplacer.replaceAllText(regularExpression, "池塘花");

    // 将文档保存到不同的PDF文件
    doc.saveToFile("out.pdf");

    // 释放资源
    doc.dispose();
    }
}

Java 在 PDF 中查找替换文本

申请临时 License

如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。

前面我们介绍了使用PdfGrid类创建表格,该文将介绍如何使用PdfTable类创建并格式化表格。

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import com.spire.pdf.tables.*;
import java.awt.*;
import java.awt.geom.Point2D;

public class CreatePDFTable {
    public static void main(String[] args) {
        //创建PDF文档
        PdfDocument doc = new PdfDocument();
        //设置margin
        PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
        PdfMargins margin = new PdfMargins();
        margin.setTop(unitCvtr.convertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point));
        margin.setBottom(margin.getTop());
        margin.setLeft(unitCvtr.convertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point));
        margin.setRight(margin.getLeft());

        // 添加一页
        PdfPageBase page = doc.getPages().add(PdfPageSize.A4, margin);

        //添加表格
        PdfTable table = new PdfTable();
        PdfSolidBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.black));
        table.getStyle().setBorderPen(new PdfPen(brush, 0.5f));
        table.getStyle().getHeaderStyle().setStringFormat(new PdfStringFormat(PdfTextAlignment.Center));
        table.getStyle().setHeaderSource(PdfHeaderSource.Rows);
        table.getStyle().setHeaderRowCount(1);
        table.getStyle().setShowHeader(true);
        table.getStyle().setCellPadding(2);
        table.getStyle().setHeaderSource(PdfHeaderSource.Rows);
        table.getStyle().setHeaderRowCount(1);
        table.getStyle().setShowHeader(true);

        //设置表头字体和样式
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("宋体",Font.PLAIN, 12));
        table.getStyle().getHeaderStyle().setFont(font);
        table.getStyle().getHeaderStyle().setBackgroundBrush(PdfBrushes.getCadetBlue());
        PdfTrueTypeFont fontBody = new PdfTrueTypeFont(new Font("宋体", Font.PLAIN,10));
        //设置偶数行字体
        table.getStyle().getDefaultStyle().setFont(fontBody);
        //设置奇数行字体
        table.getStyle().getAlternateStyle().setFont(fontBody);

        //定义数据
        String[] data = {"洲;国家;人口;世界人口占比;备注",
                "亚洲;中国;1,391,190,000;18.2%; ",
                "亚洲;日本;126,490,000;1.66%; ",
                "欧洲;英国;65,648,054;0.86%; ",
                "欧洲;德国;82,665,600;1.08%; ",
                "北美洲;加拿大;37,119,000;0.49%; ",
                "北美洲;美国;327,216,000;4.29%; "
        };
        String[][] dataSource = new String[data.length][];
        for (int i = 0; i < data.length; i++) {
            dataSource[i] = data[i].split("[;]", -1);
        }

        table.setDataSource(dataSource);
        for(int i = 0; i < table.getColumns().getCount();i++)
        {
            PdfColumn column= table.getColumns().get(i);
            column.setStringFormat(new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle));
        }

        //添加表格
        table.draw(page, new Point2D.Float(0, 50));

        //保存文档
        doc.saveToFile("output/addTable.pdf", FileFormat.PDF);
    }
}

效果图:

Java 使用 PdfTable 类创建并设置表格样式

Spire.Doc 8.12.14已发布。该版本支持获取两个Word文档之间比较出的差异,并且支持获取修订的作者和时间。此外,该版本还增强了转换Word到PDF的功能以及修复了克隆文档时出现的问题。详情请阅读以下内容。

新功能:

问题修复:


获取Spire.Doc 8.12.14,请点击:

https://www.e-iceblue.cn/Downloads/Spire-Doc-NET.html

Spire.PDF 6.12.20已发布。该版本支持通过外部服务进行数字签名并且支持设置PDF包中文件的字段并对文件进行排序。此外还增强了PDF转换到PDF/A 和PDF/A -3b的功能,以及修复了在查找文本中出现的问题。详情请阅读以下信息。

新功能:

问题修复:


获取Spire.PDF 6.12.20,请点击:

https://www.e-iceblue.cn/Downloads/Spire-PDF-NET.html

超链接是非常方便的功能,在 Word 文档中十分常见。读者只需点击超链接,就可跳转到网页、内部文件、邮箱以及正在阅读的文档中的某一部分。本文将教大家使用 Spire.Doc for Java 查找并导出 Word 文档中的超链接。

安装 Spire.Doc for Java

首先,您需要在 Java 程序中添加 Spire.Doc.jar 文件作为依赖项。您可以从 这个链接 下载 JAR 文件;如果您使用 Maven,则可以通过在 pom.xml 文件中添加以下代码导入 JAR 文件。

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.cn/repository/maven-public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc</artifactId>
        <version>14.9.5</version>
    </dependency>
</dependencies>

查找并导出 Word 文档中的指定超链接

详细操作步骤如下:

  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.Field;

import java.io.*;
import java.util.ArrayList;

public class findHyperlinks {
    public static void main(String[] args) throws IOException {
        // 创建 Document 的对象并从磁盘导入Word文档
        String input = "D:/testp/示例.docx";
        Document doc = new Document();
        doc.loadFromFile(input);

        // 创建 ArrayList<Field> 的对象
        ArrayList<Field> hyperlinks = new ArrayList<Field>();

        // 循环遍历Word文档中所有节下的 DocumentObject 对象,找到所有超链接
        for (Section section : (Iterable<Section>) doc.getSections()) {
            for (DocumentObject object : (Iterable<DocumentObject>) section.getBody().getChildObjects()) {
                if (object.getDocumentObjectType().equals(DocumentObjectType.Paragraph)) {
                    Paragraph paragraph = (Paragraph) object;
                    for (DocumentObject cObject : (Iterable<DocumentObject>) paragraph.getChildObjects()) {
                        if (cObject.getDocumentObjectType().equals(DocumentObjectType.Field)) {
                            Field field = (Field) cObject;
                            if (field.getType().equals(FieldType.Field_Hyperlink)) {
                                hyperlinks.add(field);
                            }
                        }
                    }
                }
            }
        }

        //获取第一个超链接的文本和地址
        String hyperlinksText = hyperlinks.get(0).getFieldText();
        String hyperlinkAddress = hyperlinks.get(0).getValue();

        //将第一个超链接的文本和链接地址保存到TXT文件
        String output = "D:/javaOutput/超链接文本和地址.txt";
        writeStringToText("Text:\r\n" + hyperlinksText+ "\r\n" + "Link:\r\n" + hyperlinkAddress, output);
    }

    //创建一个自定义方法将超链接文字和地址保存到TXT文件
    public static void writeStringToText(String content, String textFileName) throws IOException {
        File file = new File(textFileName);
        if (file.exists())
        {
            file.delete();
        }
        FileWriter fWriter = new FileWriter(textFileName, true);
        try {
            fWriter.write(content);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                fWriter.flush();
                fWriter.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Java 查找并导出 Word 文档中的超链接

查找并导出 Word 文档中的所有超链接

详细操作步骤如下:

  • Java
import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.Field;

import java.io.*;
import java.util.ArrayList;

public class findHyperlinks {
    public static void main(String[] args) throws IOException {
        //创建 Document 的对象并从磁盘导入Word文档
        String input = "D:/testp/示例.docx";
        Document doc = new Document();
        doc.loadFromFile(input);

        //创建 ArrayList<Field> 的对象
        ArrayList<Field> hyperlinks = new ArrayList<Field>();
        String hyperlinkText = "";
        String hyperlinkAddress = "";

        //循环遍历Word文档中所有节下的 DocumentObject 对象,找到所有超链接
        for (Section section : (Iterable<Section>) doc.getSections()) {
            for (DocumentObject object : (Iterable<DocumentObject>) section.getBody().getChildObjects()) {
                if (object.getDocumentObjectType().equals(DocumentObjectType.Paragraph)) {
                    Paragraph paragraph = (Paragraph) object;
                    for (DocumentObject cObject : (Iterable<DocumentObject>) paragraph.getChildObjects()) {
                        if (cObject.getDocumentObjectType().equals(DocumentObjectType.Field)) {
                            Field field = (Field) cObject;
                            if (field.getType().equals(FieldType.Field_Hyperlink)) {
                                hyperlinks.add(field);

                                //获取所有超链接的文本和地址
                                hyperlinkText += field.getFieldText() + "\r\n";
                                hyperlinkAddress += field.getValue() + "\r\n";
                            }
                        }
                    }
                }
            }
        }

        //将所有超链接的文本和链接地址保存到TXT文件
        String output = "D:/javaOutput/超链接文本和地址.txt";
        writeStringToText("Text:\r\n " + hyperlinkText + "\r\n" + "Link:\r\n" + hyperlinkAddress + "\r\n", output);
    }

    //创建一个自定义方法将超链接文字和地址保存到TXT文件
    public static void writeStringToText(String content, String textFileName) throws IOException {
        File file = new File(textFileName);
        if (file.exists())
        {
            file.delete();
        }
        FileWriter fWriter = new FileWriter(textFileName, true);
        try {
            fWriter.write(content);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                fWriter.flush();
                fWriter.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Java 查找并导出 Word 文档中的超链接

申请临时 License

如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。

该文将介绍如何使用Spire.PDF for java 展开或折叠书签

展开PDF文档中的所有书签

import com.spire.pdf.PdfDocument;

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

        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("Sample.pdf");

        // true为展开,false为折叠
        doc.getViewerPreferences().setBookMarkExpandOrCollapse(true);

        doc.saveToFile("output/expandAllBookmarks_out.pdf");
        doc.close();
    }
}

效果图:

Java 设置打开 PDF 文档时展开或折叠书签

仅展开特定书签

import com.spire.pdf.PdfDocument;
import com.spire.pdf.bookmarks.*;

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

        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("Sample.pdf");

        //展开第一个书签
        doc.getBookmarks().get(0).setExpandBookmark(true);

        //设置BookMarkExpandOrCollapse 为 "false" 折叠第二个书签
        PdfBookmarkCollection pdfBookmark = doc.getBookmarks().get(1);
        pdfBookmark.get(0).setExpandBookmark(false);

        doc.saveToFile("output/expandSpecificBookmarks_out.pdf");
        doc.close();
    }
}

效果图:

Java 设置打开 PDF 文档时展开或折叠书签

Spire.Doc 8.12.9已发布。该版本增强了转换Word/HTML 到PDF的功能,此外还修复了加载RTF文档时出现的问题。详情请阅读以下内容。

问题修复:


获取Spire.Doc 8.12.9,请点击:

https://www.e-iceblue.cn/Downloads/Spire-Doc-NET.html

Spire.Spreadsheet 4.12.1已发布。该版本主要修复了加载Excel文档时,抛“System.ArgumentNullException”的问题。详情请阅读以下内容。

问题修复:


获取Spire.Spreadsheet 4.12.1,请点击:

https://www.e-iceblue.cn/Downloads/Spire-Spreadsheet-NET.html

该文将详细介绍如何使用Spire.PDF for Java设置PDF 文档的页面显示样式及缩放比例。

PDF页面初始视图显示设置:

import com.spire.pdf.*;

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

        //加载示例文档
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("Sample.pdf");

        //居中窗口
        doc.getViewerPreferences().setCenterWindow(true);
        //隐藏标题
        doc.getViewerPreferences().setDisplayTitle(false);
        //不适合整页至窗口
        doc.getViewerPreferences().setFitWindow(false);
        //隐藏菜单栏
        doc.getViewerPreferences().setHideMenubar(true);
        //隐藏工具栏
        doc.getViewerPreferences().setHideToolbar(true);
        //页面布局设置为单页
        doc.getViewerPreferences().setPageLayout(PdfPageLayout.Single_Page);

        //保存文档
        String output = "output/viewerPreference.pdf";
        doc.saveToFile(output, FileFormat.PDF);
    }
}

效果图:

Java 设置 PDF 页面显示设置和缩放比例

设置PDF缩放比例

import com.spire.pdf.*;
import com.spire.pdf.actions.*;
import com.spire.pdf.general.*;

import java.awt.geom.*;

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

        //加载示例文档
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("Sample.pdf");

        //获取第一页
        PdfPageBase page = doc.getPages().get(0);

        //设置PDF页面显示位置
        PdfDestination dest = new PdfDestination(page);
        dest.setMode(PdfDestinationMode.Location);
        dest.setLocation(new Point2D.Float(-40f, -40f));

        //设置缩放比例
        dest.setZoom(0.8f);

        //设置打开PDF文档时的页面显示缩放比例
        PdfGoToAction gotoAction = new PdfGoToAction(dest);
        doc.setAfterOpenAction(gotoAction);

        //保存文档
        String output = "output/setZoomFactor.pdf";
        doc.saveToFile(output);
    }
}

效果图:

Java 设置 PDF 页面显示设置和缩放比例