Как заставить читать PDF файл как байтовый массив? - PullRequest
0 голосов
/ 20 июля 2011

После компиляции и запуска показывается «нет принтера в формате 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 ]

1 голос
/ 20 июля 2011

Вот пример того, как прочитать файл в байт []:

// 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 голос
/ 20 июля 2011

После компиляции и запуска он показывает «нет принтера в формате PDF»

Из моего прочтения документации здесь и здесь ,проблема в том, что вы не настроили поставщика услуг печати, который понимает, как печатать документы с этим DocFlavour.

Одним из решений является поиск файла JAR, который реализует SPI-файл PrinterService для документов PDF, и добавление его в путь к классам.Поиск Google покажет примеры.(Я не могу рекомендовать какой-либо конкретный SP, потому что мне никогда не приходилось его использовать. Вам нужно провести некоторое исследование / тестирование, чтобы найти тот, который подходит вам.)

0 голосов
/ 20 июля 2011
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) {
                }
        }
}
...