Java源码示例:org.sejda.io.SeekableSources
示例1
@Test
public void mergeWithHierarchy() throws IOException {
PDDocument destination = new PDDocument();
AcroFormsMerger victim = new AcroFormsMerger(AcroFormPolicy.MERGE, destination);
assertNotNull(document.getDocumentCatalog().getAcroForm());
victim.mergeForm(document.getDocumentCatalog().getAcroForm(), annotationsLookup);
mapping.clear();
annotationsLookup.clear();
try (PDDocument anotherDoc = PDFParser.parse(SeekableSources.inMemorySeekableSourceFrom(
getClass().getClassLoader().getResourceAsStream("pdf/forms/simple_form_with_hierarchy.pdf")))) {
mapping.addLookupEntry(anotherDoc.getPage(0), new PDPage());
annotationsLookup = new AnnotationsDistiller(anotherDoc).retainRelevantAnnotations(mapping);
victim.mergeForm(anotherDoc.getDocumentCatalog().getAcroForm(), annotationsLookup);
assertFalse(victim.getForm().getFields().isEmpty());
PDAcroForm form = victim.getForm();
assertNotNull(form.getField("node.leaf"));
assertEquals(5, form.getFields().size());
}
}
示例2
public static SeekableSource convertImageTo(SeekableSource source, String format) throws IOException, TaskIOException {
BufferedImage image = ImageIO.read(source.asNewInputStream());
File tmpFile = IOUtils.createTemporaryBuffer("." + format);
ImageOutputStream outputStream = new FileImageOutputStream(tmpFile);
try {
ImageWriter writer = ImageIO.getImageWritersByFormatName(format).next();
writer.setOutput(outputStream);
ImageWriteParam param = writer.getDefaultWriteParam();
if (format.equals("jpeg")) {
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(1.0F);
}
writer.write(null, new IIOImage(image, null, null), param);
} finally {
org.sejda.commons.util.IOUtils.closeQuietly(outputStream);
}
return SeekableSources.seekableSourceFrom(tmpFile);
}
示例3
@Test
public void removePopupIfGarbage() throws IOException {
try (PDDocument doc = PDFParser.parse(SeekableSources.inMemorySeekableSourceFrom(
getClass().getClassLoader().getResourceAsStream("pdf/popup_annotation.pdf")))) {
PDPage firstOrigin = doc.getPage(0);
// let's put some garbage in place of the popup
firstOrigin.getAnnotations().stream().filter(a -> !(a instanceof PDAnnotationPopup))
.forEach(a -> a.getCOSObject().setItem(COSName.POPUP, new PDPage()));
PDPage firstNew = new PDPage();
lookup.addLookupEntry(firstOrigin, firstNew);
new AnnotationsDistiller(doc).retainRelevantAnnotations(lookup);
List<PDAnnotation> annotations = firstNew.getAnnotations();
assertFalse(annotations.isEmpty());
PDAnnotationMarkup parent = annotations.stream().filter(a -> a instanceof PDAnnotationMarkup)
.map(a -> ((PDAnnotationMarkup) a)).findFirst().get();
assertNull(parent.getPopup());
}
}
示例4
@Test
// AcroForm fields array is empty. Widget is a kid of the Field dictionaries and there is no fields hierarchy
public void mergeOrphansFieldsWithWidgetKidsNoHierarchy() throws IOException {
PDDocument destination = new PDDocument();
AcroFormsMerger victim = new AcroFormsMerger(AcroFormPolicy.MERGE, destination);
mapping.clear();
annotationsLookup.clear();
try (PDDocument anotherDoc = PDFParser.parse(SeekableSources.inMemorySeekableSourceFrom(
getClass().getClassLoader().getResourceAsStream("pdf/forms/form_orphan_fields_no_hierarchy.pdf")))) {
PDPage destPage = new PDPage();
mapping.addLookupEntry(anotherDoc.getPage(0), destPage);
annotationsLookup = new AnnotationsDistiller(anotherDoc).retainRelevantAnnotations(mapping);
victim.mergeForm(anotherDoc.getDocumentCatalog().getAcroForm(), annotationsLookup);
assertEquals(2, victim.getForm().getFields().size());
assertEquals(4, destPage.getAnnotations().size());
}
}
示例5
@Test
public void pageNotFoundIncludesSourcePathAndPageNumber() throws IOException
{
try (PDDocument doc = PDFParser.parse(SeekableSources.onTempFileSeekableSourceFrom(
PDPageTreeTest.class.getResourceAsStream("with_outline.pdf"))))
{
try {
doc.getPage(99 /* 0 based */);
fail("Exception expected");
} catch (PageNotFoundException ex) {
assertEquals(ex.getPage(), 100 /* 1 based, for humans */);
assertThat(ex.getSourcePath(), containsString(File.separator + "SejdaIO"));
assertThat(ex.getSourcePath(), endsWith(".tmp"));
}
}
}
示例6
@Test
public void readTransitions() throws IOException
{
try (PDDocument doc = PDFParser
.parse(SeekableSources
.inMemorySeekableSourceFrom(getClass()
.getResourceAsStream(
"/org/sejda/sambox/pdmodel/interactive/pagenavigation/transitions_test.pdf"))))
{
PDTransition firstTransition = doc.getPages().get(0).getTransition();
assertEquals(PDTransitionStyle.Glitter.name(), firstTransition.getStyle());
assertEquals(2, firstTransition.getDuration(), 0);
assertEquals(PDTransitionDirection.TOP_LEFT_TO_BOTTOM_RIGHT.getCOSBase(),
firstTransition.getDirection());
}
}
示例7
/**
* Test document save/load using a stream.
*
* @throws IOException if something went wrong
*/
@Test
public void testSaveLoadStream() throws IOException
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// Create PDF with one blank page
try (PDDocument document = new PDDocument())
{
document.addPage(new PDPage());
document.writeTo(baos);
}
// Verify content
byte[] pdf = baos.toByteArray();
assertTrue(pdf.length > 200);
assertEquals("%PDF-1.4", new String(Arrays.copyOfRange(pdf, 0, 8), "UTF-8"));
assertEquals("%%EOF\n",
new String(Arrays.copyOfRange(pdf, pdf.length - 6, pdf.length), "UTF-8"));
// Load
try (PDDocument loadDoc = PDFParser.parse(SeekableSources.inMemorySeekableSourceFrom(pdf)))
{
assertEquals(1, loadDoc.getNumberOfPages());
}
}
示例8
@Test
public void testAccept() throws Exception {
try (PDDocument document = PDFParser.parse(SeekableSources.inMemorySeekableSourceFrom(
getClass().getClassLoader().getResourceAsStream("pdf/draw_w_transparency.pdf")))) {
document.getPages().forEach(victim::accept);
PDPage page = document.getPage(0);
COSDictionary pageRes = page.getResources().getCOSObject();
assertTrue(((COSDictionary) pageRes.getDictionaryObject(COSName.XOBJECT))
.getDictionaryObject(COSName.getPDFName("x5")).getCOSObject() instanceof ReadOnlyFilteredCOSStream);
assertTrue(((COSDictionary) pageRes.getDictionaryObject(COSName.XOBJECT))
.getDictionaryObject(COSName.getPDFName("x7")).getCOSObject() instanceof ReadOnlyFilteredCOSStream);
PDFormXObject form = (PDFormXObject) page.getResources().getXObject(COSName.getPDFName("x7"));
COSDictionary formRes = form.getResources().getCOSObject();
assertTrue("Hitter should discover forms nested in form xobjects",
((COSDictionary) formRes.getDictionaryObject(COSName.XOBJECT))
.getDictionaryObject(COSName.getPDFName("x10"))
.getCOSObject() instanceof ReadOnlyFilteredCOSStream);
PDFormXObject nestedForm = (PDFormXObject) form.getResources().getXObject(COSName.getPDFName("x10"));
COSDictionary nestedFormRes = nestedForm.getResources().getCOSObject();
assertTrue("Hitter should discover images nested in form xobjects",
((COSDictionary) nestedFormRes.getDictionaryObject(COSName.XOBJECT))
.getDictionaryObject(COSName.getPDFName("x17"))
.getCOSObject() instanceof ReadOnlyFilteredCOSStream);
}
}
示例9
@Test
public void calculationOrderIsKept() throws IOException {
PDDocument destination = new PDDocument();
AcroFormsMerger victim = new AcroFormsMerger(AcroFormPolicy.MERGE, destination);
assertNotNull(document.getDocumentCatalog().getAcroForm());
mapping.clear();
try (PDDocument anotherDoc = PDFParser.parse(SeekableSources.inMemorySeekableSourceFrom(
getClass().getClassLoader().getResourceAsStream("pdf/forms/test_form_with_calc.pdf")))) {
mapping.addLookupEntry(anotherDoc.getPage(0), new PDPage());
annotationsLookup = new AnnotationsDistiller(anotherDoc).retainRelevantAnnotations(mapping);
victim.mergeForm(anotherDoc.getDocumentCatalog().getAcroForm(), annotationsLookup);
assertEquals(2, victim.getForm().getFields().size());
assertEquals(1, victim.getForm().getCalculationOrder().size());
}
}
示例10
/**
* PDFBOX-3656
*
* Test a radio button with options. This was causing an ArrayIndexOutOfBoundsException when trying to set to "Off",
* as this wasn't treated to be a valid option.
*
* @throws IOException
*/
@Test
public void testRadioButtonWithOptions() throws IOException
{
try (PDDocument document = PDFParser.parse(
SeekableSources.inMemorySeekableSourceFrom(this.getClass().getResourceAsStream(
"/org/sejda/sambox/pdmodel/interactive/form/radio_with_options.pdf"))))
{
PDRadioButton radioButton = (PDRadioButton) document.getDocumentCatalog().getAcroForm()
.getField("Checking/Savings");
radioButton.setValue("Off");
for (PDAnnotationWidget widget : radioButton.getWidgets())
{
assertEquals("The widget should be set to Off", COSName.Off,
widget.getCOSObject().getItem(COSName.AS));
}
}
}
示例11
@Test
public void testRadioButtonWithOptionsThatDontMatchNormalAppearance() throws IOException
{
try (PDDocument document = PDFParser.parse(
SeekableSources.inMemorySeekableSourceFrom(this.getClass().getResourceAsStream(
"/org/sejda/sambox/pdmodel/interactive/form/simple_form.pdf"))))
{
PDRadioButton radioButton = (PDRadioButton) document.getDocumentCatalog().getAcroForm()
.getField("Choice_Caption_0wUBrGuJDKIWD9g7kWcKpg");
radioButton.setValue("1");
radioButton.setValue("Second Choice");
assertEquals("Export value does not exist in normal appearance. Don't export value",
radioButton.getValue(), "1");
assertEquals("First widget should be Off", COSName.Off,
radioButton.getWidgets().get(0).getCOSObject().getItem(COSName.AS));
assertEquals("Second widget should be set to 1", COSName.getPDFName("1"),
radioButton.getWidgets().get(1).getCOSObject().getItem(COSName.AS));
}
}
示例12
@Test
public void testRadioButtonWithOptionsThatDoMatchNormalAppearance() throws IOException
{
try (PDDocument document = PDFParser.parse(
SeekableSources.inMemorySeekableSourceFrom(this.getClass().getResourceAsStream(
"/org/sejda/sambox/pdmodel/interactive/form/PDFBOX-3656 - test.pdf"))))
{
PDRadioButton radioButton = (PDRadioButton) document.getDocumentCatalog().getAcroForm()
.getField("RadioButton");
radioButton.setValue("c");
assertEquals("Export value does exist in normal appearance. Do export value",
radioButton.getValue(), "c");
assertEquals("First widget should be Off", COSName.Off,
radioButton.getWidgets().get(0).getCOSObject().getItem(COSName.AS));
assertEquals("Second widget should be Off", COSName.Off,
radioButton.getWidgets().get(1).getCOSObject().getItem(COSName.AS));
assertEquals("Third widget should be set to c", COSName.getPDFName("c"),
radioButton.getWidgets().get(2).getCOSObject().getItem(COSName.AS));
}
}
示例13
@Test
public void sameFontSameInUseFontInstance() throws IOException {
try (PDDocument document = PDFParser.parse(SeekableSources.inMemorySeekableSourceFrom(
getClass().getClassLoader().getResourceAsStream("pdf/multiple_res_dic_sharing_same_font.pdf")))) {
document.getPages().forEach(victim::accept);
PDPage page0 = document.getPage(0);
InUseFontDictionary page0Font = page0.getResources().getCOSObject()
.getDictionaryObject(COSName.FONT, COSDictionary.class)
.getDictionaryObject(COSName.getPDFName("F1"), InUseFontDictionary.class);
PDPage page1 = document.getPage(1);
InUseFontDictionary page1Font = page1.getResources().getCOSObject()
.getDictionaryObject(COSName.FONT, COSDictionary.class)
.getDictionaryObject(COSName.getPDFName("F1"), InUseFontDictionary.class);
assertEquals(page0Font, page1Font);
}
}
示例14
@Test
public void doesntRemoveActionWithoutDestination() throws IOException {
try (PDDocument document = PDFParser.parse(SeekableSources.inMemorySeekableSourceFrom(
getClass().getClassLoader().getResourceAsStream("pdf/forms/simple_form_with_full_dic.pdf")))) {
PDPage page = document.getPage(0);
PDAnnotationLink link = new PDAnnotationLink();
PDActionGoTo action = new PDActionGoTo();
link.setAction(action);
page.setAnnotations(Arrays.asList(link));
PDPage copy = new PageCopier(false).copyOf(page);
assertEquals(page.getCOSObject().getDictionaryObject(COSName.ANNOTS),
page.getCOSObject().getDictionaryObject(COSName.ANNOTS));
assertNotEquals(page.getCOSObject().getDictionaryObject(COSName.ANNOTS),
copy.getCOSObject().getDictionaryObject(COSName.ANNOTS));
copy.getAnnotations().stream().map(PDAnnotation::getCOSObject).forEach(d -> {
assertFalse(d.containsKey(COSName.P));
assertFalse(d.containsKey(COSName.DEST));
assertTrue(d.containsKey(COSName.A));
});
}
}
示例15
@Test
public void testFlattenSpecificFieldsOnly() throws IOException
{
try (PDDocument doc = PDFParser
.parse(SeekableSources.inMemorySeekableSourceFrom(getClass().getResourceAsStream(
"/org/sejda/sambox/pdmodel/interactive/form/AlignmentTests.pdf"))))
{
List<PDField> fieldsToFlatten = new ArrayList<>();
PDAcroForm acroFormToFlatten = doc.getDocumentCatalog().getAcroForm();
int numFieldsBeforeFlatten = acroFormToFlatten.getFields().size();
int numWidgetsBeforeFlatten = countWidgets(doc);
fieldsToFlatten.add(acroFormToFlatten.getField("AlignLeft-Border_Small-Filled"));
fieldsToFlatten.add(acroFormToFlatten.getField("AlignLeft-Border_Medium-Filled"));
fieldsToFlatten.add(acroFormToFlatten.getField("AlignLeft-Border_Wide-Filled"));
fieldsToFlatten.add(acroFormToFlatten.getField("AlignLeft-Border_Wide_Clipped-Filled"));
acroFormToFlatten.flatten(fieldsToFlatten, true);
int numFieldsAfterFlatten = acroFormToFlatten.getFields().size();
int numWidgetsAfterFlatten = countWidgets(doc);
assertEquals(numFieldsBeforeFlatten, numFieldsAfterFlatten + fieldsToFlatten.size());
assertEquals(numWidgetsBeforeFlatten, numWidgetsAfterFlatten + fieldsToFlatten.size());
}
}
示例16
/**
* Test that we do not modify an AcroForm with missing resource information when loading the document only.
* (PDFBOX-3752)
*/
@Test
public void testDontAddMissingInformationOnDocumentLoad() throws IOException
{
try (PDDocument document = PDFParser.parse(SeekableSources
.inMemorySeekableSourceFrom(createAcroFormWithMissingResourceInformation())))
{
// do a low level access to the AcroForm to avoid the generation of missing entries
PDDocumentCatalog documentCatalog = document.getDocumentCatalog();
COSDictionary catalogDictionary = documentCatalog.getCOSObject();
COSDictionary acroFormDictionary = (COSDictionary) catalogDictionary
.getDictionaryObject(COSName.ACRO_FORM);
// ensure that the missing information has not been generated
assertNull(acroFormDictionary.getDictionaryObject(COSName.DA));
assertNull(acroFormDictionary.getDictionaryObject(COSName.RESOURCES));
}
}
示例17
@Test
public void testPDFBox3208() throws IOException
{
try (PDDocument doc = PDFParser.parse(SeekableSources.inMemorySeekableSourceFrom(getClass()
.getResourceAsStream(
"/org/sejda/sambox/input/PDFBOX-3208-L33MUTT2SVCWGCS6UIYL5TH3PNPXHIS6.pdf"))))
{
PDDocumentInformation di = doc.getDocumentInformation();
assertEquals("Liquent Enterprise Services", di.getAuthor());
assertEquals("Liquent services server", di.getCreator());
assertEquals("Amyuni PDF Converter version 4.0.0.9", di.getProducer());
assertEquals("", di.getKeywords());
assertEquals("", di.getSubject());
assertEquals("892B77DE781B4E71A1BEFB81A51A5ABC_20140326022424.docx", di.getTitle());
assertEquals(DateConverter.toCalendar("D:20140326142505-02'00'"), di.getCreationDate());
assertEquals(DateConverter.toCalendar("20140326172513Z"), di.getModificationDate());
}
}
示例18
private void doTestEncrypted(StandardSecurity security, WriteOption... options)
throws IOException
{
try (PDDocument current = PDFParser.parse(SeekableSources
.inMemorySeekableSourceFrom(getClass().getResourceAsStream(inputFile)), pwd))
{
try (ByteArrayOutputStream out = new ByteArrayOutputStream())
{
current.writeTo(out, security, options);
try (PDDocument outDoc = PDFParser.parse(
SeekableSources.inMemorySeekableSourceFrom(out.toByteArray()),
new String(security.userPassword)))
{
assertTrue(outDoc.getNumberOfPages() > 0);
}
}
}
}
示例19
@Test
public void scanBogusPrev() throws IOException
{
parser = new COSParser(SeekableSources.inMemorySeekableSourceFrom(getClass()
.getResourceAsStream("/sambox/test_multiple_xref_tables_bogus_prev.pdf")));
victim = new XrefParser(parser);
victim.parse();
assertEquals(8, victim.trailer().getCOSObject().getInt(COSName.SIZE));
assertNotNull(victim.trailer().getCOSObject().getDictionaryObject(COSName.ROOT));
COSDictionary overriddenObj = (COSDictionary) parser.provider().get(new COSObjectKey(3, 0))
.getCOSObject();
assertEquals(839, victim.trailer().xrefOffset());
assertNotNull(overriddenObj.getDictionaryObject(COSName.ANNOTS));
}
示例20
/**
* This will test the use of identity filter to decode stream and string. This test threw an IOException before the
* correction.
*
* @throws IOException
*/
public void testPDFBOX4517() throws IOException
{
PDFParser.parse(
SeekableSources
.seekableSourceFrom(new File("target/pdfs", "PDFBOX-4517-cryptfilter.pdf")),
"userpassword1234");
}
示例21
@Test
public void notEncrytedWithPwd() throws IOException
{
try (PDDocument doc = PDFParser.parse(SeekableSources.inMemorySeekableSourceFrom(
getClass().getResourceAsStream("/sambox/simple_test.pdf")), "test"))
{
assertNotNull(doc);
assertFalse(doc.isEncrypted());
assertTrue(doc.isOpen());
assertEquals(SpecVersionUtils.V1_5, doc.getVersion());
}
}
示例22
@Test
public void outlineLevels() throws IOException {
try (PDDocument doc = PDFParser.parse(
SeekableSources.inMemorySeekableSourceFrom(getClass().getResourceAsStream("/pdf/test_outline.pdf")))) {
Set<Integer> levels = OutlineUtils.getOutlineLevelsWithPageDestination(doc);
assertEquals(3, levels.size());
assertTrue(levels.contains(1));
assertTrue(levels.contains(2));
assertTrue(levels.contains(3));
}
}
示例23
@Test
public void test_LCMSError13_CouldntLinkTheProfilesError() throws IOException {
try (PDDocument doc = PDFParser.parse(SeekableSources.seekableSourceFrom(new File(TARGETPDFDIR, "PDFBOX_LCMS_Error_13.pdf")))) {
for(int i = 0; i < doc.getNumberOfPages(); i++) {
new PDFRenderer(doc).renderImage(i);
}
}
}
示例24
@Test
public void scanMissingTrailer() throws IOException
{
parser = new COSParser(SeekableSources.inMemorySeekableSourceFrom(
getClass().getResourceAsStream("/sambox/test_xref_missing_trailer.pdf")));
victim = new XrefParser(parser);
victim.parse();
assertNotNull(victim.trailer().getCOSObject().getDictionaryObject(COSName.ROOT));
assertEquals(-1, victim.trailer().xrefOffset());
}
示例25
@Test
public void headerWithSpaces() throws IOException
{
try (PDDocument doc = PDFParser.parse(SeekableSources.inMemorySeekableSourceFrom(
getClass().getResourceAsStream("/sambox/spaces_in_header.pdf"))))
{
assertNotNull(doc);
assertFalse(doc.isEncrypted());
assertTrue(doc.isOpen());
assertEquals(SpecVersionUtils.V1_4, doc.getVersion());
}
}
示例26
@Test
public void scanStreamAndTable() throws IOException
{
parser = new COSParser(SeekableSources.inMemorySeekableSourceFrom(
getClass().getResourceAsStream("/sambox/test_xref_stream_and_table.pdf")));
victim = new XrefFullScanner(parser);
victim.scan();
assertEquals(562, victim.trailer().getCOSObject().getInt(COSName.PREV));
assertEquals(9, victim.trailer().getCOSObject().getInt(COSName.SIZE));
assertNotNull(victim.trailer().getCOSObject().getDictionaryObject(COSName.ROOT));
COSDictionary overriddenObj = (COSDictionary) parser.provider().get(new COSObjectKey(3, 0))
.getCOSObject();
assertNull(overriddenObj.getDictionaryObject(COSName.ANNOTS));
assertEquals(919, victim.trailer().xrefOffset());
}
示例27
@Test
public void removesParentAndPopup() throws IOException {
try (PDDocument document = PDFParser.parse(SeekableSources.inMemorySeekableSourceFrom(
getClass().getClassLoader().getResourceAsStream("pdf/popup_annotation.pdf")))) {
PDPage page = document.getPage(0);
PDPage copy = new PageCopier(false).copyOf(page);
copy.getAnnotations().stream().map(PDAnnotation::getCOSObject).forEach(d -> {
assertFalse(d.containsKey(COSName.PARENT));
assertFalse(d.containsKey(COSName.getPDFName("Popup")));
});
}
}
示例28
@Test
public void noOutlineFlat() throws IOException {
try (PDDocument doc = PDFParser.parse(SeekableSources
.inMemorySeekableSourceFrom(getClass().getResourceAsStream("/pdf/test_no_outline.pdf")))) {
assertTrue(OutlineUtils.getFlatOutline(doc).isEmpty());
}
}
示例29
@Test
public void missingCatalog() throws IOException
{
try (PDDocument doc = PDFParser.parse(SeekableSources.inMemorySeekableSourceFrom(
getClass().getResourceAsStream("/org/sejda/sambox/input/MissingCatalog.pdf"))))
{
assertNotNull(doc);
assertFalse(doc.isEncrypted());
assertTrue(doc.isOpen());
assertEquals(SpecVersionUtils.V1_4, doc.getVersion());
assertNotNull(doc.getDocumentCatalog());
assertEquals(COSName.CATALOG,
doc.getDocumentCatalog().getCOSObject().getItem(COSName.TYPE));
}
}
示例30
/**
* PDFBOX-3068: test that indirect /Title element of /Info entry can be found.
*
* @throws Exception
*/
public void testPDFBox3068() throws Exception
{
try (PDDocument doc = PDFParser.parse(SeekableSources.inMemorySeekableSourceFrom(
getClass().getResourceAsStream("/org/sejda/sambox/pdmodel/PDFBOX-3068.pdf"))))
{
PDDocumentInformation documentInformation = doc.getDocumentInformation();
assertEquals("Title", documentInformation.getTitle());
}
}