1. Introduction
1.介绍
In this article, we’re going to explore the PDFUnit library for testing PDFs.
在这篇文章中,我们将探讨用于测试PDF的PDFUnit库。
Using the powerful APIs provided by PDFUnit, we can work with PDFs and verify text, images, bookmarks and a number of other things.
使用PDFUnit提供的强大的API,我们可以处理PDF并验证文本、图像、书签和其他一些东西。
We can eventually write quite complex test-cases using PDFUnit, but let’s start with the most common use cases that will apply to most of your production PDFs and provide an excellent base for further development.
我们最终可以使用 PDFUnit 编写相当复杂的测试案例,但让我们从最常见的用例开始,这些用例将适用于你的大多数生产的 PDF,并为进一步的开发提供一个很好的基础。
Important note: PDFUnit is available for free for evaluation purposes but not for commercial use.
重要提示:PDFUnit可免费用于评估目的,但不能用于商业用途。
2. Installation and Setup
2.安装和设置
The current version of PDFUnit (2016.05) is not available in the Maven Central repository. Hence, we need to download and install jars manually. Please follow the instructions on the official site for manual installation.
当前版本的PDFUnit(2016.05)在Maven中心仓库中不可用。因此,我们需要手动下载并安装罐子。请按照官方网站上的说明进行手动安装。
3. Number of Pages
3.页数
Let’s start with a simple example that simply validates the number of pages in a given PDF file:
让我们从一个简单的例子开始,它只是验证了一个给定的PDF文件的页数。
@Test
public void givenSinglePage_whenCheckForOnePage_thenSuccess() {
String filename = getFilePath("sample.pdf");
AssertThat.document(filename)
.hasNumberOfPages(1);
}
The getFilePath() is a simple method, not related to PDFUnit, which simply returns the path of the PDF file as a String.
getFilePath()是一个简单的方法,与PDFUnit无关,它只是将PDF文件的路径作为一个String返回。
All the PDFUnit tests start with a call to AssertThat.document() which prepares the document for testing. The hasNumberOfPages() takes an int as the argument which specifies the number of pages the PDF must contain. In our case, the file sample.pdf contains only one page, so the test succeeds.
所有的PDFUnit测试都是从调用AssertThat.document()开始的,它为测试准备了文档。hasNumberOfPages()需要一个int作为参数,指定PDF必须包含的页数。在我们的例子中,文件sample.pdf只包含一页,所以测试成功。
If the actual number of pages does not match with the argument, an exception is thrown.
如果实际页数与参数不一致,就会出现异常。
Let’s see an example on how to test a scenario when an exception is thrown:
让我们看一个例子,如何在抛出异常时测试一个场景。
@Test(expected = PDFUnitValidationException.class)
public void givenMultiplePages_whenCheckForOnePage_thenException() {
String filename = getFilePath("multiple_pages.pdf");
AssertThat.document(filename)
.hasNumberOfPages(1);
}
In this case, the file multiple_pages.pdf contains multiple pages. Hence a PDFUnitValidationException exception is thrown.
在这种情况下,文件multiple_pages.pdf包含多个页面。因此,一个PDFUnitValidationException异常被抛出。
4. Password Protected Files
4.受密码保护的文件
Handling password protected files is again really simple. The only difference is in the call to AssertThat.document() where we need to pass a second argument which is the password of the file:
处理受密码保护的文件也是非常简单的。唯一的区别是对AssertThat.document()的调用,我们需要传递第二个参数,即文件的密码。
@Test
public void givenPwdProtected_whenOpenWithPwd_thenSuccess() {
String filename = getFilePath("password_protected.pdf");
String userPassword = "pass1";
AssertThat.document(filename, userPassword)
.hasNumberOfPages(1);
}
5. Text Comparison
5.文本比较
Let’s now compare a test PDF (sample.pdf) against a reference PDF (sample_reference.pdf). If the text of the file under test is same as the reference file, then the test succeeds:
现在让我们把一个测试的PDF(sample.pdf)和一个参考的PDF(sample_reference.pdf)进行比较。如果被测文件的文本与参考文件相同,那么测试就成功了。
@Test
public void whenMatchWithReferenceFile_thenSuccess() {
String testFileName = getFilePath("sample.pdf");
String referenceFileName = getFilePath("sample_reference.pdf");
AssertThat.document(testFileName)
.and(referenceFileName)
.haveSameText();
}
The haveSameText() is the method that does all the work of comparing the text between the two files.
haveSameText()是完成两个文件之间文本比较的所有工作的方法。
If we don’t want to compare the complete text between two files and instead, want to validate the existence of a particular text on a certain page, the containing() method comes handy:
如果我们不想在两个文件之间比较完整的文本,而是想在某个页面上验证某个特定文本的存在,那么containing()方法就很方便。
@Test
public void whenPage2HasExpectedText_thenSuccess() {
String filename = getFilePath("multiple_pages.pdf");
String expectedText = "Chapter 1, content";
AssertThat.document(filename)
.restrictedTo(PagesToUse.getPage(2))
.hasText()
.containing(expectedText);
}
The above test succeeds if the Page #2 of the multiple_pages.pdf file contains the expectedText anywhere on the page. The absence or presence of any other text apart from the expectedText does not affect the results.
如果multiple_pages.pdf文件的第2页在页面的任何地方包含expectedText,上述测试就会成功。除了预期文本之外,没有或存在任何其他文本都不会影响结果。
Let’s now make the test more restrictive by validating if a particular text is present in a certain region of a page instead of the whole page. For this, we need to understand the concept of PageRegion.
现在让我们通过验证一个特定的文本是否存在于一个页面的某个区域而不是整个页面,使测试更具限制性。为此,我们需要了解PageRegion的概念。
A PageRegion is a rectangular sub-section within the actual page under test. The PageRegion must completely fall under the actual page. If any portion of PageRegion falls outside the actual page, it will result in an error.
一个PageRegion是被测试的实际页面中的一个矩形子段。PageRegion必须完全位于实际页面的下方。如果PageRegion的任何部分落在实际页面之外,它将导致一个错误。
A PageRegion is defined by four elements:
一个PageRegion由四个元素定义。
- leftX – the number of millimeters a verticle line is away from the leftmost vertical edge of the page
- upperY – the number of millimeters a horizontal line is away from the topmost horizontal edge of the page
- width – the width of the region in millimeters
- height – the height of the region millimeters
To understand this concept better, let us create a PageRegion using the following attributes:
为了更好地理解这个概念,让我们使用以下属性创建一个PageRegion。
- leftX = 20
- upperY = 10
- width = 150
- height = 50
Here is an approximate image representation of the above PageRegion:
下面是上述PageRegion的近似图像表示:。
Once the concept is clear, the corresponding test case is relatively simpler:
一旦概念明确,相应的测试用例就会相对简单。
@Test
public void whenPageRegionHasExpectedtext_thenSuccess() {
String filename = getFilePath("sample.pdf");
int leftX = 20;
int upperY = 10;
int width = 150;
int height = 50;
PageRegion regionTitle = new PageRegion(leftX, upperY, width, height);
AssertThat.document(filename)
.restrictedTo(PagesToUse.getPage(1))
.restrictedTo(regionTitle)
.hasText()
.containing("Adobe Acrobat PDF Files");
}
Here, we have created a PageRegion within page #1 of the PDF file and verified the text in this region.
在这里,我们在PDF文件的第1页内创建了一个PageRegion,并验证了这个区域内的文本。
6. Bookmarks
6.书签
Let’s see a couple of bookmark related test cases:
让我们看看几个与书签有关的测试案例。
@Test
public void whenHasBookmarks_thenSuccess() {
String filename = getFilePath("with_bookmarks.pdf");
AssertThat.document(filename)
.hasNumberOfBookmarks(5);
}
This test will succeed if the PDF file has exactly five bookmarks.
如果PDF文件正好有五个书签,这个测试将成功。
The label of bookmarks can be verified as well:
书签的标签也可以被核实。
@Test
public void whenHasBookmarksWithLabel_thenSuccess() {
String filename = getFilePath("with_bookmarks.pdf");
AssertThat.document(filename)
.hasBookmark()
.withLabel("Chapter 2")
.hasBookmark()
.withLinkToPage(3);
}
Here we are checking that the given PDF has a bookmark with the text “Chapter 2”. It also verifies if there is a bookmark that links to Page #3.
这里我们要检查给定的PDF是否有一个带有 “第二章 “文字的书签。它还验证是否有一个链接到第3页的书签。
7. Images
7.图像
Images are another important aspect of PDF documents. Unit testing the images inside the PDF again very easy:
图片是PDF文档的另一个重要方面。对PDF内的图像进行单元测试又非常容易。
@Test
public void whenHas2DifferentImages_thenSuccess() {
String filename = getFilePath("with_images.pdf");
AssertThat.document(filename)
.hasNumberOfDifferentImages(2);
}
This test verifies that there are exactly two different images utilized inside the PDF. The number of different images refers to an actual number of images stored inside a PDF document.
这个测试验证了PDF中正好有两个不同的图像被使用。不同图像的数量是指存储在PDF文档中的图像的实际数量。
However, it could be possible that there is a single logo image stored inside the document but is displayed on every page of the document. This refers to the number of visible images, which can be more than the number of different images.
然而,有可能有一个单一的标志图像存储在文件内,但却显示在文件的每一页。这指的是可见图像的数量,可能比不同图像的数量要多。
Let’s see how to verify the visible images:
让我们看看如何验证可见的图像。
@Test
public void whenHas2VisibleImages_thenSuccess() {
String filename = getFilePath("with_images.pdf");
AssertThat.document(filename)
.hasNumberOfVisibleImages(2);
}
PDFUnit is powerful enough to compare the content of images byte-by-byte. This also means that the image in the PDF and the reference image must be exactly equal.
PDFUnit强大到可以逐个字节地比较图像的内容。这也意味着,PDF中的图像和参考图像必须完全相等。
Because of byte comparison, different format of images like BMP and PNG are considered unequal:
由于字节的比较,不同格式的图像如BMP和PNG被认为是不平等的。
@Test
public void whenImageIsOnAnyPage_thenSuccess() {
String filename = getFilePath("with_images.pdf");
String imageFile = getFilePath("Superman.png");
AssertThat.document(filename)
.restrictedTo(AnyPage.getPreparedInstance())
.hasImage()
.matching(imageFile);
}
Notice the use of AnyPage here. We are not restricting the occurrence of the image to any particular page, rather on any page in the entire document.
注意这里使用的是AnyPage。我们不是将图像的出现限制在任何特定的页面上,而是限制在整个文档的任何页面上。
The image to compare can take the form of BufferedImage, File, InputStream, or URL apart from the String that represents the file name.
要比较的图像可以采取BufferedImage、File、InputStream或URL的形式,除了代表文件名的String。
8. Embedded Files
8.嵌入式文件
Certain PDF documents come with embedded files or attachments. It is necessary to test those as well:
某些PDF文件带有嵌入式文件或附件。也有必要对这些文件进行测试。
@Test
public void whenHasEmbeddedFile_thenSuccess() {
String filename = getFilePath("with_attachments.pdf");
AssertThat.document(filename)
.hasEmbeddedFile();
}
This will verify if the document under test has at least one embedded file.
这将验证被测试的文件是否至少有一个嵌入式文件。
We can verify the name of the embedded file as well:
我们也可以验证嵌入式文件的名称。
@Test
public void whenHasmultipleEmbeddedFiles_thenSuccess() {
String filename = getFilePath("with_attachments.pdf");
AssertThat.document(filename)
.hasNumberOfEmbeddedFiles(4)
.hasEmbeddedFile()
.withName("complaintform1.xls")
.hasEmbeddedFile()
.withName("complaintform2.xls")
.hasEmbeddedFile()
.withName("complaintform3.xls");
}
We can move one step further and verify the content of the embedded files as well:
我们可以更进一步,也可以验证嵌入文件的内容:。
@Test
public void whenEmbeddedFileContentMatches_thenSuccess() {
String filename = getFilePath("with_attachments.pdf");
String embeddedFileName = getFilePath("complaintform1.xls");
AssertThat.document(filename)
.hasEmbeddedFile()
.withContent(embeddedFileName);
}
All the examples in this section are relatively straightforward and self-explanatory.
本节中的所有例子都是相对直接和不言自明的。
9. Conclusion
9.结论
In this tutorial, we’ve seen several examples that cover the most common use cases related to PDF testing.
在本教程中,我们已经看到了几个例子,涵盖了与PDF测试有关的最常见的使用情况。
However, there is a lot more PDFUnit can do; make sure to visit the documentation page to learn more.
然而,PDFUnit能做的事情还有很多;请确保访问文档页面以了解更多。