Skip to content
Advertisement

Convert pdf to Postscript using Java

I recently posted a question how to convert a PDF byte[] to Postscript. According to comment, it’s not possible.

I was anyway looking into this other question on how to transform a pdf to Postscript. But still cannot get it working.

I got my PDF saved already, how would I get an already existing PDF converted to Postscript? Any way modifying this code below to achieve result?

import java.io.File;
import java.io.FileOutputStream;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.SimpleDoc;
import javax.print.StreamPrintService;
import javax.print.StreamPrintServiceFactory;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;

public class Printing {


        public static void main(String[] args) {
            try {
            DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
            String psMimeType = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();
            StreamPrintServiceFactory[] factories = StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor, psMimeType);

            System.out.println ("Available PS services: " + factories.length);
            System.out.println ("Format: " + factories[0].getOutputFormat());

            FileOutputStream outStream = new FileOutputStream("/path/to/your.ps");
            StreamPrintService printService = factories[0].getPrintService(outStream);


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

            PDDocument doc = PDDocument.load(new File("/path/to/my.pdf"));

            SimpleDoc pdfDoc = new SimpleDoc(new PDFPrintable(doc, Scaling.SCALE_TO_FIT, false), flavor, null);

            DocPrintJob newJob = printService.createPrintJob();
            newJob.print(pdfDoc, aset);

            outStream.close();

            }
            catch(Exception ex) {
                ex.printStackTrace();
            }
        }
}

Edit: I tried to modify according to comment, but it crashes when I try to load File f:

public static void MakePS(String pathToPdf) throws PrinterException, IOException, PrintException {
            DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
            DocAttributeSet daset = new HashDocAttributeSet();

            StreamPrintServiceFactory[] factories =
                    StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor,
                            DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType());
            if (factories.length == 0) {
                throw new PrinterException("No PostScript factories available");
            }
            File f = new File(pathToPdf);
            PDDocument document = null;
            try {
                document = PDDocument.load(f);
            } catch (IOException e) {
                System.out.println("Cannot load file to pdf document");
                e.printStackTrace();
            };

            // 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(pathToPdf);
            factories[0].getPrintService(fos).createPrintJob().print(
                    new SimpleDoc(new PDFPrintable(document, Scaling.ACTUAL_SIZE, false), flavor, daset), aset);
            fos.close();
            document.close();
        }

I get following error when trying PDDocument.load(f):

16:37:05,448 ERROR [stderr] (pool-15-thread-1) Exception in thread "pool-15-thread-1" java.lang.NoClassDefFoundError: org/apache/pdfbox/pdmodel/PDDocument
16:37:05,449 ERROR [stderr] (pool-15-thread-1)  at com.app.servlet.PdfToPsFile.MakePS(PdfToPsFile.java:168)
16:37:05,450 ERROR [stderr] (pool-15-thread-1)  at com.app.servlet.PrintServlet.lambda$doGet$1(PrintServlet.java:151)
16:37:05,451 ERROR [stderr] (pool-15-thread-1)  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
16:37:05,451 ERROR [stderr] (pool-15-thread-1)  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
16:37:05,452 ERROR [stderr] (pool-15-thread-1)  at java.lang.Thread.run(Thread.java:748)
16:37:05,453 ERROR [stderr] (pool-15-thread-1) Caused by: java.lang.ClassNotFoundException: org.apache.pdfbox.pdmodel.PDDocument from [Module ".war:main" from Service Module Loader]
16:37:05,454 ERROR [stderr] (pool-15-thread-1)  at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:211)
16:37:05,455 ERROR [stderr] (pool-15-thread-1)  at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:459)
16:37:05,456 ERROR [stderr] (pool-15-thread-1)  at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:408)
16:37:05,457 ERROR [stderr] (pool-15-thread-1)  at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:389)
16:37:05,457 ERROR [stderr] (pool-15-thread-1)  at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:134)
ยดยดยด

Advertisement

Answer

Tilman Hausherr provided correct answer to the issue that I encountered. I can produce one page PS file so far with this code. But will not produce additional pages. I in this post that you can print via Postscript commands somehow, which will not bloat the file. Will have to look into this later on. First try solve how to add additional pages. Here is the code:

public static void MakePSFile(String pathToPdf) {
        try {
            DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
            String psMimeType = DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType();
            StreamPrintServiceFactory[] factories = StreamPrintServiceFactory.lookupStreamPrintServiceFactories(flavor, psMimeType);

            System.out.println("Available PS services: " + factories.length);
            System.out.println("Format: " + factories[0].getOutputFormat());

            FileOutputStream outStream = new FileOutputStream("c:/psFile.ps");
            StreamPrintService printService = factories[0].getPrintService(outStream);


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

            PDDocument doc = PDDocument.load(new File(pathToPdf));

            SimpleDoc pdfDoc = new SimpleDoc(new PDFPrintable(doc, Scaling.SCALE_TO_FIT, false), flavor, null);

            DocPrintJob newJob = printService.createPrintJob();
            newJob.print(pdfDoc, aset);

            outStream.close();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement