如何将PDF文件读取为字节数组?

时间:2011-07-20 06:27:15

标签: java printing tcpdf

编译运行后显示“没有pdf打印机可用”,如何解决?

  

我在c:\ print.pdf中创建了一个文件(使用PHP TCPDF)。我是   试图在字节数组中读取该文件,以便我可以静默打印   它没有显示任何印刷品等。

     

我无法让它工作,任何人都可以请指导如何阅读   文件在字节数组?要执行以下操作:

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;

public class print 
{
    private static Object pdfBytes;

    // Byte array reader 
    public static byte[] getBytesFromFile(File file) throws IOException {
        InputStream is = new FileInputStream(file);
        long length = file.length();
        if (length > Integer.MAX_VALUE) {}
        byte[] bytes = new byte[(int)length];

        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
               && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
            offset += numRead;
        }
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "+file.getName());
        }
        is.close();
        return bytes;
    }    

    // Convert Byte array to Object 
    public static Object toObject(byte[] bytes) 
    {
        Object obj = null;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream (bis);
            obj = ois.readObject();
        } catch (IOException ex) {

        } catch (ClassNotFoundException ex) {

        }
        return obj;
    }

    private static File fl = new File("c:\\print.pdf");    
    public static void main(String argc[])
    {
        DocFlavor flavor = DocFlavor.BYTE_ARRAY.PDF;
        PrintService[] services = 
                PrintServiceLookup.lookupPrintServices(flavor,
                null);
        //Object pdfBytes = null;
        try {
            byte[] abc = getBytesFromFile(fl);
            pdfBytes =toObject(abc);
        } catch (IOException ex) {
            Logger.getLogger(print.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (services.length>0)
        {
            DocPrintJob printJob = services[0].createPrintJob();
            Doc document = new SimpleDoc(pdfBytes,flavor,null);
            try {
                printJob.print(document, null);
            } catch (PrintException ex) {
                Logger.getLogger(print.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            System.out.println("no pdf printer available");

        }
    }

}

我尝试了这个,它解决了我的无声打印:https://gist.github.com/1094612

3 个答案:

答案 0 :(得分:1)

以下是如何将文件读入byte []的示例:

// Returns the contents of the file in a byte array.
public static byte[] getBytesFromFile(File file) throws IOException {
    InputStream is = new FileInputStream(file);

    // Get the size of the file
    long length = file.length();

    // You cannot create an array using a long type.
    // It needs to be an int type.
    // Before converting to an int type, check
    // to ensure that file is not larger than Integer.MAX_VALUE.
    if (length > Integer.MAX_VALUE) {
        // File is too large
    }

    // Create the byte array to hold the data
    byte[] bytes = new byte[(int)length];

    // Read in the bytes
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length
           && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
        offset += numRead;
    }

    // Ensure all the bytes have been read in
    if (offset < bytes.length) {
        throw new IOException("Could not completely read file "+file.getName());
    }

    // Close the input stream and return bytes
    is.close();
    return bytes;
}

答案 1 :(得分:1)

  

编译运行后,显示“没有可用的pdf打印机”

在阅读文档herehere时,问题是您尚未配置了解如何使用该DocFlavour打印文档的打印服务提供商。

一种解决方案是找到一个JAR文件,该文件为PDF文档实现PrinterService SPI并将其添加到类路径中。 Google搜索会显示示例。 (我不能推荐任何特定的SP,因为我从来没有使用过。你需要做一些调查/测试才能找到适合你的。)

答案 2 :(得分:0)

import java.io.*;
import java.util.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;

public class ReadPDFFile {
        public static void main(String[] args) throws IOException {
                try {
                        Document document = new Document();
                        document.open();
                        PdfReader reader = new PdfReader("file.pdf");
                        PdfDictionary dictionary = reader.getPageN(1);
                        PRIndirectReference reference = (PRIndirectReference) dictionary
                                        .get(PdfName.CONTENTS);
                        PRStream stream = (PRStream) PdfReader.getPdfObject(reference);
                        byte[] bytes = PdfReader.getStreamBytes(stream);
                        PRTokeniser tokenizer = new PRTokeniser(bytes);
                        StringBuffer buffer = new StringBuffer();
                        while (tokenizer.nextToken()) {
                                if (tokenizer.getTokenType() == PRTokeniser.TK_STRING) {
                                        buffer.append(tokenizer.getStringValue());
                                }
                        }
                        String test = buffer.toString();
                        System.out.println(test);
                } catch (Exception e) {
                }
        }
}