Java Code Examples for org.apache.pdfbox.io.IOUtils#copy()

The following examples show how to use org.apache.pdfbox.io.IOUtils#copy() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Overlay.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
private COSStream createCombinedContentStream(COSBase contents) throws IOException
{
    List<COSStream> contentStreams = createContentStreamList(contents);
    // concatenate streams
    COSStream concatStream = inputPDFDocument.getDocument().createCOSStream();
    OutputStream out = concatStream.createOutputStream(COSName.FLATE_DECODE);
    for (COSStream contentStream : contentStreams)
    {
        InputStream in = contentStream.createInputStream();
        IOUtils.copy(in, out);
        out.flush();
        in.close();
    }
    out.close();
    return concatStream;
}
 
Example 2
Source File: PdfManipulatorTest.java    From estatio with Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example 3
Source File: ASCII85Filter.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public DecodeResult decode(InputStream encoded, OutputStream decoded,
                                     COSDictionary parameters, int index) throws IOException
{
    ASCII85InputStream is = null;
    try
    {
        is = new ASCII85InputStream(encoded);
        IOUtils.copy(is, decoded);
        decoded.flush();
    }
    finally
    {
        IOUtils.closeQuietly(is);
    }
    return new DecodeResult(parameters);
}
 
Example 4
Source File: COSStream.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Returns the contents of the stream as a PDF "text string".
 * 
 * @return the text string representation of this stream.
 */
public String toTextString()
{
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    InputStream input = null;
    try
    {
        input = createInputStream();
        IOUtils.copy(input, out);
    }
    catch (IOException e)
    {
        return "";
    }
    finally
    {
        IOUtils.closeQuietly(input);
    }
    COSString string = new COSString(out.toByteArray());
    return string.getString();
}
 
Example 5
Source File: COSWriter.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Write externally created signature of PDF data obtained via {@link #getDataToSign()} method.
 *
 * @param cmsSignature CMS signature byte array
 * @throws IllegalStateException if PDF is not prepared for external signing
 * @throws IOException if source data stream is closed
 */
public void writeExternalSignature(byte[] cmsSignature) throws IOException {

    if (incrementPart == null || incrementalInput == null)
    {
        throw new IllegalStateException("PDF not prepared for setting signature");
    }
    byte[] signatureBytes = Hex.getBytes(cmsSignature);

    // substract 2 bytes because of the enclosing "<>"
    if (signatureBytes.length > signatureLength - 2)
    {
        throw new IOException("Can't write signature, not enough space");
    }

    // overwrite the signature Contents in the buffer
    int incPartSigOffset = (int) (signatureOffset - incrementalInput.length());
    System.arraycopy(signatureBytes, 0, incrementPart, incPartSigOffset + 1, signatureBytes.length);

    // write the data to the incremental output stream
    IOUtils.copy(new RandomAccessInputStream(incrementalInput), incrementalOutput);
    incrementalOutput.write(incrementPart);

    // prevent further use
    incrementPart = null;
}
 
Example 6
Source File: PDStream.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * This will copy the stream into a byte array.
 * 
 * @return The byte array of the filteredStream.
 * @throws IOException if an I/O error occurs.
 */
public byte[] toByteArray() throws IOException
{
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    InputStream is = null;
    try
    {
        is = createInputStream();
        IOUtils.copy(is, output);
    } 
    finally
    {
        if (is != null)
        {
            is.close();
        }
    }
    return output.toByteArray();
}
 
Example 7
Source File: PDStream.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Constructor. Reads all data from the input stream and embeds it into the document with the
 * given filters applied, if any. This method closes the InputStream.
 */
private PDStream(PDDocument doc, InputStream input, COSBase filters) throws IOException
{
    OutputStream output = null;
    try
    {
        stream = doc.getDocument().createCOSStream();
        output = stream.createOutputStream(filters);
        IOUtils.copy(input, output);
    }
    finally
    {
        if (output != null)
        {
            output.close();
        }
        if (input != null)
        {
            input.close();
        }
    }
}
 
Example 8
Source File: PDImageXObject.java    From gcs with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Creates a COS stream from raw (encoded) data.
 */
private static COSStream createRawStream(PDDocument document, InputStream rawInput)
        throws IOException
{
    COSStream stream = document.getDocument().createCOSStream();
    OutputStream output = null;
    try
    {
        output = stream.createRawOutputStream();
        IOUtils.copy(rawInput, output);
    }
    finally
    {
        if (output != null)
        {
            output.close();
        }
    }
    return stream;
}
 
Example 9
Source File: COSWriter.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Write an incremental update for a non signature case. This can be used for e.g. augmenting
 * signatures.
 *
 * @throws IOException
 */
private void doWriteIncrement() throws IOException
{
    // write existing PDF
    IOUtils.copy(new RandomAccessInputStream(incrementalInput), incrementalOutput);
    // write the actual incremental update
    incrementalOutput.write(((ByteArrayOutputStream) output).toByteArray());
}
 
Example 10
Source File: COSWriter.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public Object visitFromStream(COSStream obj) throws IOException
{
    if (willEncrypt)
    {
        pdDocument.getEncryption().getSecurityHandler()
            .encryptStream(obj, currentObjectKey.getNumber(), currentObjectKey.getGeneration());
    }

    InputStream input = null;
    try
    {
        // write the stream content
        visitFromDictionary(obj);
        getStandardOutput().write(STREAM);
        getStandardOutput().writeCRLF();

        input = obj.createRawInputStream();
        IOUtils.copy(input, getStandardOutput());
     
        getStandardOutput().writeCRLF();
        getStandardOutput().write(ENDSTREAM);
        getStandardOutput().writeEOL();
        return null;
    }
    finally
    {
        if (input != null)
        {
            input.close();
        }
    }
}
 
Example 11
Source File: IdentityFilter.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public DecodeResult decode(InputStream encoded, OutputStream decoded,
                                     COSDictionary parameters, int index)
    throws IOException
{
    IOUtils.copy(encoded, decoded);
    decoded.flush();
    return new DecodeResult(parameters);
}
 
Example 12
Source File: IdentityFilter.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
@Override
protected void encode(InputStream input, OutputStream encoded, COSDictionary parameters)
    throws IOException
{
    IOUtils.copy(input, encoded);
    encoded.flush();
}
 
Example 13
Source File: ASCII85Filter.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
@Override
protected void encode(InputStream input, OutputStream encoded, COSDictionary parameters)
    throws IOException
{
    ASCII85OutputStream os = new ASCII85OutputStream(encoded);
    IOUtils.copy(input, os);
    os.close();
    encoded.flush();
}
 
Example 14
Source File: CCITTFaxFilter.java    From gcs with Mozilla Public License 2.0 5 votes vote down vote up
@Override
protected void encode(InputStream input, OutputStream encoded, COSDictionary parameters)
        throws IOException
{
    int cols = parameters.getInt(COSName.COLUMNS);
    int rows = parameters.getInt(COSName.ROWS);
    CCITTFaxEncoderStream ccittFaxEncoderStream = 
            new CCITTFaxEncoderStream(encoded, cols, rows, TIFFExtension.FILL_LEFT_TO_RIGHT);
    IOUtils.copy(input, ccittFaxEncoderStream);
    input.close();
}
 
Example 15
Source File: CreateMultipleVisualizations.java    From testarea-pdfbox2 with Apache License 2.0 5 votes vote down vote up
@Override
public void write(OutputStream out) throws IOException, CMSException
{
    // read the content only one time
    IOUtils.copy(in, out);
    in.close();
}
 
Example 16
Source File: SecurityHandler.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
/**
 * Encrypt or decrypt data with AES256.
 *
 * @param data The data to encrypt.
 * @param output The output to write the encrypted data to.
 * @param decrypt true to decrypt the data, false to encrypt it.
 *
 * @throws IOException If there is an error reading the data.
 */
private void encryptDataAES256(InputStream data, OutputStream output, boolean decrypt) throws IOException
{
    byte[] iv = new byte[16];

    if (!prepareAESInitializationVector(decrypt, iv, data, output))
    {
        return;
    }

    Cipher cipher;
    try
    {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(encryptionKey, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        cipher.init(decrypt ? Cipher.DECRYPT_MODE : Cipher.ENCRYPT_MODE, keySpec, ivSpec);
    }
    catch (GeneralSecurityException e)
    {
        throw new IOException(e);
    }

    CipherInputStream cis = new CipherInputStream(data, cipher);
    try
    {
        IOUtils.copy(cis, output);
    }
    catch(IOException exception)
    {
        // starting with java 8 the JVM wraps an IOException around a GeneralSecurityException
        // it should be safe to swallow a GeneralSecurityException
        if (!(exception.getCause() instanceof GeneralSecurityException))
        {
            throw exception;
        }
        LOG.debug("A GeneralSecurityException occured when decrypting some stream data", exception);
    }
    finally
    {
        cis.close();
    }
}
 
Example 17
Source File: Predictor.java    From gcs with Mozilla Public License 2.0 4 votes vote down vote up
static void decodePredictor(int predictor, int colors, int bitsPerComponent, int columns, InputStream in, OutputStream out)
        throws IOException
{
    if (predictor == 1)
    {
        // no prediction
        IOUtils.copy(in, out);
    }
    else
    {
        // calculate sizes
        final int rowlength = calculateRowLength(colors, bitsPerComponent, columns);
        byte[] actline = new byte[rowlength];
        byte[] lastline = new byte[rowlength];

        int linepredictor = predictor;

        while (in.available() > 0)
        {
            // test for PNG predictor; each value >= 10 (not only 15) indicates usage of PNG predictor
            if (predictor >= 10)
            {
                // PNG predictor; each row starts with predictor type (0, 1, 2, 3, 4)
                // read per line predictor
                linepredictor = in.read();
                if (linepredictor == -1)
                {
                    return;
                }
                // add 10 to tread value 0 as 10, 1 as 11, ...
                linepredictor += 10;
            }

            // read line
            int i, offset = 0;
            while (offset < rowlength && ((i = in.read(actline, offset, rowlength - offset)) != -1))
            {
                offset += i;
            }

            decodePredictorRow(linepredictor, colors, bitsPerComponent, columns, actline, lastline);
            System.arraycopy(actline, 0, lastline, 0, rowlength);
            out.write(actline);
        }
    }
}