How to convert a PDF to a postscript file using pdfbox 2.0

霸气de小男生 提交于 2021-01-28 02:20:30

问题


I was able to create a PDF with PDFBox (version 1.8.9) and then convert it to a PostScript file with the following code:

    DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
    StreamPrintServiceFactory[] factories =
            StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor,
                    DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType());
    if (factories.length == 0) {
        throw new PrinterException("No PostScript factories available");
    }
    PDDocument document = pdfGenerator.getDocument();

    // Attributes are specified by https://docs.oracle.com/javase/7/docs/api/
    // see package javax.print.attribute.standard
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    aset.add(MediaSizeName.NA_LETTER);
    aset.add(new PageRanges(1, document.getNumberOfPages()));

    FileOutputStream fos = new FileOutputStream(filePathAndName);
    factories[0].getPrintService(fos).createPrintJob().print(
            new SimpleDoc(new PDPageable(document), flavor, null), aset);
    fos.close();
    document.close();

The PDPageable object doesn't seem to be in the PDFBox 2.0 code and I didn't see it specified in the migration document. How do I convert a PDF file to a PostScript file using PDFBox 2.0?

Thank you


回答1:


You are right, in PDFBox the version 1.18.12 Package org.apache.pdfbox.pdmodel has a PDPageable class, but the corresponding version 2.0.3 Package org.apache.pdfbox.pdmodel does not.

But what you want to to do is convert to a PostScript language document. I think PDFPrintable will do that for you.

See this other SO question, Printing to PostScript with PDFBox produces a massive file, why?, for a code snippet that shows PDFPrintable in use. I've simplified it a bit and included it below. Does it look familiar to you? :-)

PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    aset.add(MediaSizeName.NA_LETTER);

FileOutputStream fos = new FileOutputStream(filePathAndName);
StreamPrintService sps = factories[0].getPrintService(fos);
        DocPrintJob dpj = sps.createPrintJob();
        SimpleDoc sd = new SimpleDoc(new PDFPrintable(document, Scaling.ACTUAL_SIZE, false), flavor, null);
        factories[0].getPrintService(fos).createPrintJob().print(
                new SimpleDoc(new PDFPrintable(document, Scaling.ACTUAL_SIZE, false), flavor, daset), aset);
fos.close();
document.close();


来源:https://stackoverflow.com/questions/38380341/how-to-convert-a-pdf-to-a-postscript-file-using-pdfbox-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!