本文整理汇总了Java中org.apache.pdfbox.io.IOUtils类的典型用法代码示例。如果您正苦于以下问题:Java IOUtils类的具体用法?Java IOUtils怎么用?Java IOUtils使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
IOUtils类属于org.apache.pdfbox.io包,在下文中一共展示了IOUtils类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testPlaceByBoundingBox
import org.apache.pdfbox.io.IOUtils; //导入依赖的package包/类
/**
* <a href="https://stackoverflow.com/questions/47383506/pdfbox-obtain-bounding-box-of-rotated-image">
* PDFBox - obtain bounding box of rotated image
* </a>
* <p>
* This test demonstrates how to position images given their dimensions,
* rotation angle, and the coordinates of the lower left corner of their
* bounding box. The work horse is {@link #placeImage(PDDocument, PDPage,
* PDImageXObject, float, float, float, float, float)}.
* </p>
*/
@Test
public void testPlaceByBoundingBox() throws IOException {
try ( InputStream resource = getClass().getResourceAsStream("Willi-1.jpg");
PDDocument document = new PDDocument() ) {
PDPage page = new PDPage();
document.addPage(page);
PDRectangle mediaBox = page.getMediaBox();
float bbLowerLeftX = 50;
float bbLowerLeftY = 100;
try ( PDPageContentStream contentStream = new PDPageContentStream(document, page) ) {
contentStream.moveTo(bbLowerLeftX, mediaBox.getLowerLeftY());
contentStream.lineTo(bbLowerLeftX, mediaBox.getUpperRightY());
contentStream.moveTo(mediaBox.getLowerLeftX(), bbLowerLeftY);
contentStream.lineTo(mediaBox.getUpperRightX(), bbLowerLeftY);
contentStream.stroke();
}
PDImageXObject image = PDImageXObject.createFromByteArray(document, IOUtils.toByteArray(resource), "Image");
placeImage(document, page, image, bbLowerLeftX, bbLowerLeftY, image.getWidth(), image.getHeight(), (float)(Math.PI/4));
placeImage(document, page, image, bbLowerLeftX, bbLowerLeftY, .5f*image.getWidth(), .5f*image.getHeight(), 0);
placeImage(document, page, image, bbLowerLeftX, bbLowerLeftY, .25f*image.getWidth(), .25f*image.getHeight(), (float)(9*Math.PI/8));
document.save(new File(RESULT_FOLDER, "rotatedImagesByBoundingBox.pdf"));
}
}
示例2: getProcessDefinitionDiagramById
import org.apache.pdfbox.io.IOUtils; //导入依赖的package包/类
public static byte[] getProcessDefinitionDiagramById(String processDefinitionId) throws Exception {
ProcessDefinition pd = repositoryService
.createProcessDefinitionQuery()
.processDefinitionId( processDefinitionId )
.singleResult();
if (pd == null) {
return null;
}
byte data[] = null;
ProcessDefinitionEntity pde = (ProcessDefinitionEntity)pd;
InputStream is = repositoryService.getResourceAsStream(pde.getDeploymentId(), pde.getDiagramResourceName());
data = IOUtils.toByteArray(is);
is.close();
is = null;
return data;
}
示例3: bigGeneratorTest
import org.apache.pdfbox.io.IOUtils; //导入依赖的package包/类
@Test
@Ignore("for generation and manual testing")
public void bigGeneratorTest() throws Exception {
SignatureImageParameters signatureImageParameters = createSignatureImageParameters();
for (SignatureImageParameters.VisualSignatureRotation rotation : SignatureImageParameters.VisualSignatureRotation.values()) {
for (SignatureImageParameters.VisualSignatureAlignmentHorizontal horizontal : SignatureImageParameters.VisualSignatureAlignmentHorizontal
.values()) {
for (SignatureImageParameters.VisualSignatureAlignmentVertical vertical : SignatureImageParameters.VisualSignatureAlignmentVertical.values()) {
signatureImageParameters.setRotation(rotation);
signatureImageParameters.setAlignmentHorizontal(horizontal);
signatureImageParameters.setAlignmentVertical(vertical);
String[] pdfs = new String[] { "normal", "90", "180", "270" };
for (String pdf : pdfs) {
DSSDocument document = sign(signablePdfs.get(pdf));
File checkPdfFile = new File(
"target/pdf/check_" + rotation.name() + "_" + pdf + "_" + horizontal.name() + "_" + vertical.name() + ".pdf");
checkPdfFile.getParentFile().mkdirs();
IOUtils.copy(document.openStream(), new FileOutputStream(checkPdfFile));
}
}
}
}
}
示例4: testDummySignInMemory
import org.apache.pdfbox.io.IOUtils; //导入依赖的package包/类
/**
* <a href="http://stackoverflow.com/questions/29123436/how-to-sign-an-inputstream-from-a-pdf-file-with-pdfbox-2-0-0">
* How to sign an InputStream from a PDF file with PDFBox 2.0.0
* </a>
*
* Test the equivalent for PDFBox 1.8.8. Works alright.
*/
@Test
public void testDummySignInMemory() throws IOException, COSVisitorException, SignatureException
{
try ( InputStream sourceStream = getClass().getResourceAsStream("/mkl/testarea/pdfbox1/assembly/document1.pdf");
OutputStream output = new FileOutputStream(new File(RESULT_FOLDER, "document1-with-dummy-sig.pdf")))
{
byte[] input = IOUtils.toByteArray(sourceStream);
output.write(input);
signDetached(input, output, new SignatureInterface()
{
@Override
public byte[] sign(InputStream content) throws SignatureException, IOException
{
return "Test".getBytes();
}
});
}
}
示例5: test
import org.apache.pdfbox.io.IOUtils; //导入依赖的package包/类
void test(String resourceName, File resultFile) throws IOException, COSVisitorException, CertificateEncodingException
{
try ( InputStream source = getClass().getResourceAsStream(resourceName);
FileOutputStream fos = new FileOutputStream(resultFile);
FileInputStream fis = new FileInputStream(resultFile);
)
{
List<byte[]> certificates = new ArrayList<byte[]>();
for (int i = 0; i < cert.length; i++)
certificates.add(cert[i].getEncoded());
COSDictionary dss = createDssDictionary(certificates, null, null);
byte inputBytes[] = IOUtils.toByteArray(source);
PDDocument pdDocument = PDDocument.load(new ByteArrayInputStream(inputBytes));
PDDocumentCatalog catalog = pdDocument.getDocumentCatalog();
catalog.getCOSObject().setNeedToBeUpdate(true);
catalog.getCOSDictionary().setItem(COSName.getPDFName("DSS"), dss);
fos.write(inputBytes);
pdDocument.saveIncremental(fis, fos);
pdDocument.close();
}
}
示例6: download
import org.apache.pdfbox.io.IOUtils; //导入依赖的package包/类
@Override
public byte[] download( String prefix, Long id, String format ) throws InvoiceServiceException
{
try
{
InputStream in = storeService.downloadFile( blobStoreFileFactory.produce( format, prefix, id ) );
if ( in == null ) throw new InvoiceMissingException();
return IOUtils.toByteArray( in );
}
catch ( IOException e )
{
throw new InvoiceServiceException( e );
}
}
示例7: firstPageOf
import org.apache.pdfbox.io.IOUtils; //导入依赖的package包/类
@Ignore
@Test
public void firstPageOf() throws Exception {
URL resource = Resources.getResource(PdfManipulatorTest.class, "sample-invoice.pdf");
byte[] bytes = Resources.toByteArray(resource);
Stamp stamp = new Stamp(Arrays.asList(
"approved by: Joe Bloggs",
"approved on: 3-May-2017 14:15",
"doc barcode: 3013011234"
), Arrays.asList(
"debtor IBAN: FR12345678900000123",
"crdtor IBAN: FR99999912312399800",
"gross amt : 12345.99"
), "http://www.google.com");
final PdfManipulator pdfManipulator = new PdfManipulator();
pdfManipulator.pdfBoxService = new PdfBoxService();
//stamp = null;
byte[] firstPageBytes = pdfManipulator.extractAndStamp(bytes, new ExtractSpec(3,1), stamp);
IOUtils.copy(new ByteArrayInputStream(firstPageBytes), new FileOutputStream("x.pdf"));
}
示例8: process
import org.apache.pdfbox.io.IOUtils; //导入依赖的package包/类
@Override
public void process(ExamPaper examPaper) {
try {
examPaper.setPageImages(pdfProcessor.getPageImages(examPaper));
examPaper.setQRCodeString(pdfProcessor.readQRCode(examPaper));
} catch (PdfException | NotFoundException ex) {
exceptionLogger.logException(ex);
LOGGER.debug("QR-koodia ei pystytty lukemaan.");
if (saveOnExamPaperPDFError) {
try {
InputStream stream = new ByteArrayInputStream(examPaper.getPdf());
fileSaver.saveInputStream(stream, saveErrorFolder, "" + System.currentTimeMillis() + ".pdf");
IOUtils.closeQuietly(stream);
LOGGER.debug("Tallennettin virheellinen PDF.");
} catch (FileAlreadyExistsException ex1) {
exceptionLogger.logException(ex);
}
}
// Don't continue if we couldn't read QR code.
return;
}
processNextStages(examPaper);
}
示例9: registerFont
import org.apache.pdfbox.io.IOUtils; //导入依赖的package包/类
/**
* Register a font. If possible, try to use a font file, i.e.
* {@link #registerFont(String,File)}. This method will lead to the creation of
* a temporary file which stores the font data.
*
* @param fontName
* the name of the font to use. If null, the name is taken from the
* font.
* @param fontStream
* the input stream of the font. This file must be a ttf/otf file!
* You have to close the stream outside, this method will not close
* the stream.
*/
@SuppressWarnings("WeakerAccess")
public void registerFont(String fontName, InputStream fontStream) throws IOException {
File fontFile = File.createTempFile("pdfboxgfx2dfont", ".ttf");
FileOutputStream out = new FileOutputStream(fontFile);
try {
IOUtils.copy(fontStream, out);
} finally {
out.close();
}
fontFile.deleteOnExit();
tempFiles.add(fontFile);
registerFont(fontName, fontFile);
}
示例10: signWithSeparatedHashing
import org.apache.pdfbox.io.IOUtils; //导入依赖的package包/类
/**
* <a href="http://stackoverflow.com/questions/41767351/create-pkcs7-signature-from-file-digest">
* Create pkcs7 signature from file digest
* </a>
* <p>
* The OP's <code>sign</code> method after fixing some errors. The
* OP's original method is {@link #signBySnox(InputStream)}. The
* errors were
* </p>
* <ul>
* <li>multiple attempts at reading the {@link InputStream} parameter;
* <li>convoluted creation of final CMS container.
* </ul>
* <p>
* Additionally this method uses SHA256 instead of SHA-1.
* </p>
*/
public byte[] signWithSeparatedHashing(InputStream content) throws IOException
{
try
{
// Digest generation step
MessageDigest md = MessageDigest.getInstance("SHA256", "BC");
byte[] digest = md.digest(IOUtils.toByteArray(content));
// Separate signature container creation step
List<Certificate> certList = Arrays.asList(chain);
JcaCertStore certs = new JcaCertStore(certList);
CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
Attribute attr = new Attribute(CMSAttributes.messageDigest,
new DERSet(new DEROctetString(digest)));
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(attr);
SignerInfoGeneratorBuilder builder = new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider())
.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(new AttributeTable(v)));
AlgorithmIdentifier sha256withRSA = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
InputStream in = new ByteArrayInputStream(chain[0].getEncoded());
X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);
gen.addSignerInfoGenerator(builder.build(
new BcRSAContentSignerBuilder(sha256withRSA,
new DefaultDigestAlgorithmIdentifierFinder().find(sha256withRSA))
.build(PrivateKeyFactory.createKey(pk.getEncoded())),
new JcaX509CertificateHolder(cert)));
gen.addCertificates(certs);
CMSSignedData s = gen.generate(new CMSAbsentContent(), false);
return s.getEncoded();
}
catch (Exception e)
{
e.printStackTrace();
throw new IOException(e);
}
}
示例11: testValidateSignatureVlidationTest
import org.apache.pdfbox.io.IOUtils; //导入依赖的package包/类
/**
* <a href="http://stackoverflow.com/questions/41116833/pdf-signature-validation">
* PDF Signature Validation
* </a>
* <br/>
* <a href="https://drive.google.com/file/d/0BzEmZ9pRWLhPOUJSYUdlRjg2eEU/view?usp=sharing">
* SignatureVlidationTest.pdf
* </a>
* <p>
* The code completely ignores the <b>SubFilter</b> of the signature.
* It is appropriate for signatures with <b>SubFilter</b> values
* <b>adbe.pkcs7.detached</b> and <b>ETSI.CAdES.detached</b>
* but will fail for signatures with <b>SubFilter</b> values
* <b>adbe.pkcs7.sha1</b> and <b>adbe.x509.rsa.sha1</b>.
* </p>
* <p>
* The example document has been signed with a signatures with
* <b>SubFilter</b> value <b>adbe.pkcs7.sha1</b>.
* </p>
*/
@Test
public void testValidateSignatureVlidationTest() throws Exception
{
System.out.println("\nValidate signature in SignatureVlidationTest.pdf; original code.");
byte[] pdfByte;
PDDocument pdfDoc = null;
SignerInformationVerifier verifier = null;
try
{
pdfByte = IOUtils.toByteArray(this.getClass().getResourceAsStream("SignatureVlidationTest.pdf"));
pdfDoc = PDDocument.load(new ByteArrayInputStream(pdfByte));
PDSignature signature = pdfDoc.getSignatureDictionaries().get(0);
byte[] signatureAsBytes = signature.getContents(pdfByte);
byte[] signedContentAsBytes = signature.getSignedContent(pdfByte);
CMSSignedData cms = new CMSSignedData(new CMSProcessableByteArray(signedContentAsBytes), signatureAsBytes);
SignerInformation signerInfo = (SignerInformation) cms.getSignerInfos().getSigners().iterator().next();
X509CertificateHolder cert = (X509CertificateHolder) cms.getCertificates().getMatches(signerInfo.getSID())
.iterator().next();
verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider()).build(cert);
// result if false
boolean verifyRt = signerInfo.verify(verifier);
System.out.println("Verify result: " + verifyRt);
}
finally
{
if (pdfDoc != null)
{
pdfDoc.close();
}
}
}
示例12: testValidateSignatureVlidationTestAdbePkcs7Sha1
import org.apache.pdfbox.io.IOUtils; //导入依赖的package包/类
/**
* <a href="http://stackoverflow.com/questions/41116833/pdf-signature-validation">
* PDF Signature Validation
* </a>
* <br/>
* <a href="https://drive.google.com/file/d/0BzEmZ9pRWLhPOUJSYUdlRjg2eEU/view?usp=sharing">
* SignatureVlidationTest.pdf
* </a>
* <p>
* This code also ignores the <b>SubFilter</b> of the signature,
* it is appropriate for signatures with <b>SubFilter</b> value
* <b>adbe.pkcs7.sha1</b> which the example document has been
* signed with.
* </p>
*/
@Test
public void testValidateSignatureVlidationTestAdbePkcs7Sha1() throws Exception
{
System.out.println("\nValidate signature in SignatureVlidationTest.pdf; special adbe.pkcs7.sha1 code.");
byte[] pdfByte;
PDDocument pdfDoc = null;
SignerInformationVerifier verifier = null;
try
{
pdfByte = IOUtils.toByteArray(this.getClass().getResourceAsStream("SignatureVlidationTest.pdf"));
pdfDoc = PDDocument.load(new ByteArrayInputStream(pdfByte));
PDSignature signature = pdfDoc.getSignatureDictionaries().get(0);
byte[] signatureAsBytes = signature.getContents(pdfByte);
CMSSignedData cms = new CMSSignedData(new ByteArrayInputStream(signatureAsBytes));
SignerInformation signerInfo = (SignerInformation) cms.getSignerInfos().getSigners().iterator().next();
X509CertificateHolder cert = (X509CertificateHolder) cms.getCertificates().getMatches(signerInfo.getSID())
.iterator().next();
verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider()).build(cert);
boolean verifyRt = signerInfo.verify(verifier);
System.out.println("Verify result: " + verifyRt);
byte[] signedContentAsBytes = signature.getSignedContent(pdfByte);
MessageDigest md = MessageDigest.getInstance("SHA1");
byte[] calculatedDigest = md.digest(signedContentAsBytes);
byte[] signedDigest = (byte[]) cms.getSignedContent().getContent();
System.out.println("Document digest equals: " + Arrays.equals(calculatedDigest, signedDigest));
}
finally
{
if (pdfDoc != null)
{
pdfDoc.close();
}
}
}
示例13: getDiagramByte
import org.apache.pdfbox.io.IOUtils; //导入依赖的package包/类
private static byte[] getDiagramByte(ProcessInstance pi) throws Exception {
byte[] data = null;
ProcessDiagramGenerator processDiagramGenerator = new DefaultProcessDiagramGenerator();
BpmnModel model = repositoryService.getBpmnModel(pi.getProcessDefinitionId());
InputStream is = processDiagramGenerator.generateDiagram(
model,
"png",
runtimeService.getActiveActivityIds(pi.getId()));
data = IOUtils.toByteArray(is);
is.close();
is = null;
return data;
}
示例14: rotateTest
import org.apache.pdfbox.io.IOUtils; //导入依赖的package包/类
@Test
@Ignore("for generation and manual testing")
public void rotateTest() throws Exception {
SignatureImageParameters signatureImageParameters = createSignatureImageParameters();
signatureImageParameters.setRotation(SignatureImageParameters.VisualSignatureRotation.AUTOMATIC);
DSSDocument document = sign(signablePdfs.get("minoltaScan90"));
File checkPdfFile = new File("target/pdf/check.pdf");
checkPdfFile.getParentFile().mkdirs();
IOUtils.copy(document.openStream(), new FileOutputStream(checkPdfFile));
}
示例15: validateForPrint
import org.apache.pdfbox.io.IOUtils; //导入依赖的package包/类
/**
* @param pdfStream the input stream for reading the PDF. It will be closed before returning from
* this method
* @param readStrategy decides if PDF is completely read into memory or not
*/
private PdfValidationResult validateForPrint(InputStream pdfStream, PdfValidationSettings printValidationSettings, PdfValidateStrategy readStrategy) {
int numberOfPages = -1;
try {
List<PdfValidationError> errors;
try {
if (readStrategy == NON_SEQUENTIALLY) {
try (EnhancedNonSequentialPDFParser dpostNonSequentialPDFParser = new EnhancedNonSequentialPDFParser(pdfStream)){
numberOfPages = dpostNonSequentialPDFParser.getNumberOfPages();
errors = validateStreamForPrint(dpostNonSequentialPDFParser, printValidationSettings);
}
} else if (readStrategy == FULLY_IN_MEMORY) {
try (PDDocument pdDoc = PDDocument.load(pdfStream)) {
numberOfPages = pdDoc.getNumberOfPages();
errors = validateDocumentForPrint(pdDoc, printValidationSettings);
}
} else {
throw new IllegalArgumentException("Unknown " + PdfValidateStrategy.class.getSimpleName() + ": " + readStrategy);
}
} catch (Exception e) {
errors = asList(PdfValidationError.PDF_PARSE_ERROR);
LOG.info("PDF could not be parsed. (" + e.getMessage() + ")");
LOG.debug(e.getMessage(), e);
}
return new PdfValidationResult(errors, numberOfPages, printValidationSettings.bleed);
} finally {
IOUtils.closeQuietly(pdfStream);
}
}