# Ausdruck mit pdfBox macht Probleme



## Thomas Lorenz (24. Sep 2010)

Hallo Gemeinde, 

die folgende Klasse soll im Idealfall ein PDF-Dokument ausdrucken.
Aber es kommt stattdessen diese Meldung : 

java.lang.reflect.InvocationTargetException
	at java.awt.EventQueue.invokeAndWait(EventQueue.java:1034)
	at apple.awt.CPrinterJob.printAndGetPageFormatArea(CPrinterJob.java:627)
	at apple.awt.CPrinterJob._safePrintLoop(Native Method)
	at apple.awt.CPrinterJob.access$900(CPrinterJob.java:22)
	at apple.awt.CPrinterJob$7.run(CPrinterJob.java:638)
Caused by: java.lang.NoClassDefFoundError: org/apache/fontbox/afm/AFMParser
	at org.apache.pdfbox.pdmodel.font.PDFont.addAdobeFontMetric(PDFont.java:124)
	at org.apache.pdfbox.pdmodel.font.PDFont.getAdobeFontMetrics(PDFont.java:98)
	at org.apache.pdfbox.pdmodel.font.PDFont.<clinit>(PDFont.java:93)
	at org.apache.pdfbox.pdmodel.font.PDFontFactory.createFont(PDFontFactory.java:140)
	at org.apache.pdfbox.pdmodel.font.PDFontFactory.createFont(PDFontFactory.java:76)
	at org.apache.pdfbox.pdmodel.PDResources.getFonts(PDResources.java:115)
	at org.apache.pdfbox.util.PDFStreamEngine.processSubStream(PDFStreamEngine.java:227)
	at org.apache.pdfbox.util.PDFStreamEngine.processStream(PDFStreamEngine.java:208)
	at org.apache.pdfbox.pdfviewer.PageDrawer.drawPage(PageDrawer.java:112)
	at org.apache.pdfbox.pdmodel.PDPage.print(PDPage.java:821)
	at apple.awt.CPrinterJob$6.run(CPrinterJob.java:619)
	at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:199)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:633)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
	at apple.awt.EventDispatchAccess.pumpEventsAndWait(Native Method)
	at apple.awt.CPrinterJob.print(CPrinterJob.java:209)
	at sun.print.RasterPrinterJob.print(RasterPrinterJob.java:1251)
	at org.apache.pdfbox.pdmodel.PDDocument.print(PDDocument.java:1005)
	at _Pol649.PDFViewer.actionPerformed(PDFViewer.java:191)
	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2028)
	at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2351)
	at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
	at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
	at java.awt.Component.processMouseEvent(Component.java:6348)
	at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
	at java.awt.Component.processEvent(Component.java:6113)
	at java.awt.Container.processEvent(Container.java:2085)
	at java.awt.Component.dispatchEventImpl(Component.java:4714)
	at java.awt.Container.dispatchEventImpl(Container.java:2143)
	at java.awt.Component.dispatchEvent(Component.java:4544)
	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4618)
	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4282)
	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4212)
	at java.awt.Container.dispatchEventImpl(Container.java:2129)
	at java.awt.Window.dispatchEventImpl(Window.java:2478)
	at java.awt.Component.dispatchEvent(Component.java:4544)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:635)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Caused by: java.lang.ClassNotFoundException: org.apache.fontbox.afm.AFMParser
	at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
	... 48 more


Hier die Klasse:

```
package _Pol649;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import org.apache.pdfbox.pdmodel.PDDocument;

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;

/**
 * An example of drawing a PDF to an image.
 * 
 * @author [email]joshua.marinacci@sun.com[/email]
 */
public class PDFViewer implements ActionListener ,Printable {

    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    JPanel pan_center = new JPanel();
    JPanel pan_south = new JPanel();

    JScrollPane scroll = new JScrollPane(pan_center);
    JButton bt_close = new JButton("zurück");
    JButton bt_print = new JButton("Pol 649 drucken");

    private ArrayList<Image> imageList = new ArrayList<Image>();
    // Eine ArrayList für die Klassen, von denen diese Klasse aufgerufen wird
    public static ArrayList<Object> arrayList = new ArrayList<Object>();
    SystemData _Sys = (SystemData) CollectionController.getObject("SystemData");
    File pdf;
    File originalPDF;
    RandomAccessFile raf;
    FileChannel channel;
    ByteBuffer buf;
    PDFFile pdffile;

    int sides = 0;
    String fileName = "";
    ArrayList<JLabel> list = new ArrayList<JLabel>();

    // Ein Konstruktor für die ReportTable
    public PDFViewer(File pdfFileOriginal) throws IOException {
	this.pdf = pdfFileOriginal;
	this.raf = new RandomAccessFile(this.pdf, "r");
	this.channel = raf.getChannel();
	this.buf = channel
		.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
	this.pdffile = new PDFFile(buf);
	// Die Anzahl der Seiten
	this.sides = pdffile.getNumPages() + 1;
	// Der Name fÃ¼r die Titelleiste des Frames
	this.fileName = pdfFileOriginal.toString().substring(
		pdfFileOriginal.toString().lastIndexOf("/") + 1,
		pdfFileOriginal.toString().length());
	this.originalPDF = pdfFileOriginal;
	setup();
    }

    public Container addComponentsToPane() {
	Container pane = frame.getContentPane();
	panel.setLayout(new BorderLayout());
	panel.setBackground(_Sys.getBackground());
	// Das GridLayout benÃ¶tigt die Seitenanzahl vom pdf-File
	pan_center.setLayout(new GridLayout(sides - 1, 1));
	pan_center.setBackground(_Sys.getBackground());
	// Das Scrollen beschleunigen
	scroll.getVerticalScrollBar().setUnitIncrement(16);
	// Die Seiten vom PDFFile fangen bei 1 an
	for (int i = 1; i < pdffile.getNumPages() + 1; i++){
	    // draw the first page to an image
	    PDFPage page = pdffile.getPage(i);

	    // get the width and height for the doc at the default zoom
	    Rectangle rect = new Rectangle(0, 0, (int) page.getBBox()
		    .getWidth(), (int) page.getBBox().getHeight());

	    // Die Bilder in doppelter GrÃ¶ÃŸe erzeugen
	    Image img = page.getImage(rect.width * 2, rect.height * 2, // width
		    // &
		    // height
		    rect, // clip rect
		    null, // null for the ImageObserver
		    true, // fill background with white
		    true // block until drawing is done
		    );
	    imageList.add(img);
	    /*
	     * Wenn das Drucken eines 649 aus der Recherche, oder aus der
	     * Verwaltung geschieht, dann wird der Zusatz 'zur Information'
	     * hinzugefügt.
	     */

	    if (arrayList.get(0).toString().contains("InvestigationFrame")
		    || arrayList.get(0).toString().contains("AdminReportTable"))
	    {
		AffineTransform trans = AffineTransform.getRotateInstance(0,
			rect.width >> 1, rect.height >> 1);
		Graphics2D graph = (Graphics2D) img.getGraphics();
		graph.setFont(new Font("ARIAL", Font.BOLD, 30));
		graph.setColor(Color.black);
		graph.setTransform(trans);
		graph.drawString("-- zur Information --", 450, 60);
	    }

	    // Die ArrayList mit Labeln fÃ¼llen
	    list.add(new JLabel(new ImageIcon(img)));

	    // Die Bilder der ArrayList in das Panel legen
	    pan_center.add(list.get(i - 1));
	}
	panel.add(scroll, BorderLayout.CENTER);
	pan_south.setLayout(new GridLayout(1, 4));
	pan_south.setBackground(_Sys.getBackground());
	pan_south.add(new JLabel());
	pan_south.add(bt_close);
	bt_close.addActionListener(this);
	bt_print.addActionListener(this);

	pan_south.add(bt_print);
	pan_south.add(new JLabel());
	panel.add(pan_south, BorderLayout.SOUTH);
	pane.add(panel);
	return pane;
    }

    public void setup() throws IOException {
	frame.setContentPane(addComponentsToPane());
	frame.setBackground(_Sys.getStandardBackground());
	frame.setTitle(this.fileName);
	frame.setSize(1240, 900);
	frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
	frame.setVisible(true);
	frame.setResizable(false);
	frame.setLocationRelativeTo(null);

    }

    public void showPDFFile(String fileName) {

	try{
	    PDFViewer image = new PDFViewer(new File(fileName));
	    image.setup();
	}
	catch (IOException e){
	    // TODO Auto-generated catch block
	    e.printStackTrace();
	}

    }

    public void actionPerformed(ActionEvent e) {
	if (e.getSource() == this.bt_print){
	    PDDocument document = null;
	    try{
		SystemData _Sys =(SystemData)CollectionController.getObject("SystemData");
		String printFile = _Sys.getUserIndex() + pdf.getName();
		System.out.println(printFile);
		document = PDDocument.load("/Users/thomaslorenz/Desktop/test.pdf");
		PrinterJob printJob = PrinterJob.getPrinterJob();
	   	try{
		    document.print(printJob);
		}
		catch (PrinterException e1){
		    // TODO Auto-generated catch block
		    e1.printStackTrace();
		}
		finally
		    {
			if(document != null)
			    {
			    document.close();
			    }
		    }
	    }
	    
	    catch (IOException u){
		// TODO Auto-generated catch block
		u.printStackTrace();
	    }
	    
	    

	}

	/*
	 * Je nachdem von welcher Klasse aus das Drucken ausgeführt wird, muss
	 * dann auch der aufrufende Frame wird auf 'enabled' geschaltet werden.
	 */
	if (e.getSource() == this.bt_close){
	    this.frame.dispose();
	    if (arrayList.get(0).toString().contains("ReportDataTable")){
		ReportDataTable report = (ReportDataTable) arrayList.get(0);
		report.frame.setEnabled(true);
		report.frame.setVisible(true);

	    }
	    if (arrayList.get(0).toString().contains(
		    "_Investigation.InvestigationFrame"))
	    {
		_Investigation.InvestigationFrame report = (_Investigation.InvestigationFrame) arrayList
			.get(0);
		report.frame.setEnabled(true);
		report.frame.setVisible(true);

	    }
	    if (arrayList.get(0).toString().contains("AdminReportTable")){
		AdminReportTable report = (AdminReportTable) arrayList.get(0);
		report.frame.setEnabled(true);
		report.frame.setVisible(true);

	    }
	    if (arrayList.get(0).toString().contains("MainFrame")){
		MainFrame report = (MainFrame) arrayList.get(0);
		report.Main.setEnabled(true);
		report.Main.setVisible(true);

	    }
	    arrayList.clear();
	}

    }

    
    public int print(Graphics arg0, PageFormat arg1, int arg2)
	    throws PrinterException
    {

	if (imageList.size() > 0)
	    return NO_SUCH_PAGE;

	try{
	    Graphics2D g2 = (Graphics2D) arg0;
	    BufferedImage buf = (BufferedImage) imageList.get(0);
	    g2.drawImage(buf, 400, 400, null);

	}
	catch (Exception e){
	    return NO_SUCH_PAGE;
	}
	return PAGE_EXISTS;

    }

}
```

Und drucken tut er nur eine leere Seite.


----------



## Marcinek (24. Sep 2010)

Er beschwert sich, weil ihm eine Klasse fehlt:

Caused by: java.lang.NoClassDefFoundError: org/apache/fontbox/afm/AFMParser

Maybe eine jar, die im Classpath fehlt.


----------



## Thomas Lorenz (25. Sep 2010)

Eine Kleinigkeit für Dich, aber eine große Hilfe für mich.
Darum bekommst Du ein Dankeschön.

Gruss Thomas


----------

