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

发布于 2024-11-24 21:18:10 字数 3039 浏览 2 评论 0原文

编译运行后显示“没有可用的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< /a>

After compile and run it shows "no pdf printer available", How to solve this?

I have created a file in c:\print.pdf (using PHP TCPDF). And i am
trying to read that file in byte array, so that i can silently print
it without showing any popup of print etc.

I cant make it working, can anyone please show guide how to read a
file in Byte array? To do the following:

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");

        }
    }

}

I tried this and it solves my silent printing: https://gist.github.com/1094612

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

谈下烟灰 2024-12-01 21:18:10

以下是如何将文件读入 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;
}

Here's an example on how to read a file into a 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;
}
很快妥协 2024-12-01 21:18:10
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) {
                }
        }
}
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) {
                }
        }
}
吹梦到西洲 2024-12-01 21:18:10

编译并运行后显示“no pdf Printer available”

从我阅读的文档 这里此处,问题是您尚未配置了解如何使用该 DocFlavour 打印文档的打印服务提供程序。

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

After compile and run it shows "no pdf printer available"

From my reading of the documentation here and here, the problem is you haven't configured print service provider that understands how to print documents with that DocFlavour.

One solution is to find a JAR file that implements the PrinterService SPI for PDF documents and add it to your classpath. A Google search will show examples. (I can't recommend any particular SP because I've never had to use one. You'll need to do some investigation / testing to find one that works for you.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文