PDF Ausdruck auf Drucker - Probleme mit Format

hebein

Mitglied
Hallo,
bitte ich bräuchte dringend Hilfe.
Ich möchte ein Tool umsetzen, dass mir Etiketten für Covid19-PCR-Teströhrchen erstellt.
Den Barcode bekomme ich einwandfrei zusammen.
Wenn ich das PDF dann aber drucken möchte, meckert mein Brother-Drucker:
Es ist ein 38mm endlos etikett eingelegt, das PDF ist im Format richtig:
1649162558026.png



1649162369484.png

public class PrintBrother
{
private static final double paper_width_mm = 38;
private static final double paper_height_mm = 15;

public void print (PDDocument document, String inName) throws NullPointerException, IllegalArgumentException, PrinterException
{
PrintService printService = findPrintService("Brother QL-600");


PrinterJob job = PrinterJob.getPrinterJob();

job.setPrintService(printService);
job.setPageable(new PDPageable(document));
job.print();

}

private static PrintService findPrintService(String printerName) {
PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
for (PrintService printService : printServices) {
if (printService.getName().trim().equals(printerName)) {
return printService;
}
}
return null;
}

}
 

Anhänge

Wo setzt Du denn die Größe? Wie kommst Du zu dem PDocument? Hast Du mal im document die Pages geprüft und Dir von allen Seiten des Dokumentes die diversen Box-Größen angesehen? (MediaBox. CropBox, BBox, ..... Ich habe gerade keinen Überblick, was da wie wichtig ist. Habe mit PDFBox noch nicht so viel gemacht)
 
Wo setzt Du denn die Größe? Wie kommst Du zu dem PDocument? Hast Du mal im document die Pages geprüft und Dir von allen Seiten des Dokumentes die diversen Box-Größen angesehen? (MediaBox. CropBox, BBox, ..... Ich habe gerade keinen Überblick, was da wie wichtig ist. Habe mit PDFBox noch nicht so viel gemacht)
Die Boxgrössen sind alle identisch mit
MEDIA W: 107.71654
MEDIA H: 42.519688
BLEED W: 107.71654
BLEED H: 42.519688
CROP W: 107.71654
CROP H: 42.519688
TRIM W: 107.71654
TRIM H: 42.519688

Den Barcode erzeuge ich hier:

import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import java.awt.Color;
import java.io.File;
import java.io.FileNotFoundException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import java.awt.image.BufferedImage;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap;
import org.apache.pdfbox.pdmodel.graphics.xobject.PDXObjectImage;



/**
*
* @author deedarali.broohi
*/
public class BarCode {
static final float MM_TO_POINT = 2.834645669f;
private static final float width = 38;
private static final float height = 15;

private static final int offset_Text_x = 10;
private static final int offset_Text_y = 30;

private static final int offset_Code_x = 10;
private static final int offset_Code_y = 20;
private static final float size_font_Code = 10;
private static final float size_font_Text = 15;

public static void main(String[] args) throws Exception {
BarCode barcode = new BarCode();
barcode.createBarCode("AG", "Antigen");
}

public void createBarCode(String barCode, String message) throws Exception {

String millisecond = String.valueOf(System.currentTimeMillis());
millisecond = millisecond.substring(3,10);

barCode = barCode+""+millisecond;

BitMatrix bitMatrix;

String directory = "C:\\Users\\GuntherBackoffice\\Downloads\\";
String outputFileName = directory+message+""+millisecond+".pdf";
File outPutFile = new File(outputFileName);

PDDocument document = new PDDocument();
PDPage page = new PDPage(new PDRectangle(width * MM_TO_POINT, height * MM_TO_POINT));
page.setCropBox(new PDRectangle(width * MM_TO_POINT, height * MM_TO_POINT));

document.addPage(page);
// Create a new font object selecting one of the PDF base fonts
PDFont fontMono = PDType1Font.COURIER_BOLD;
// Start a new content stream which will "hold" the to be created content
PDPageContentStream cos = new PDPageContentStream(document, page);

System.out.println ("BLEED W: "+page.getBleedBox().getWidth());
System.out.println ("BLEED H: "+page.getBleedBox().getHeight());
System.out.println ("CROP W: "+page.getCropBox().getWidth());
System.out.println ("CROP H: "+page.getCropBox().getHeight());
System.out.println ("TRIM W: "+page.getTrimBox().getWidth());
System.out.println ("TRIM H: "+page.getTrimBox().getHeight());
System.out.println ("MEDIA W: "+page.getMediaBox().getWidth());
System.out.println ("MEDIA H: "+page.getMediaBox().getHeight());



int margin = 90;
try {

float startX = page.getMediaBox().getWidth()/2;
float startY = page.getMediaBox().getHeight()/2;

cos.beginText();
cos.setFont(fontMono, size_font_Text);
cos.setNonStrokingColor(Color.BLACK);
cos.moveTextPositionByAmount(offset_Text_x,offset_Text_y);
cos.drawString(message);
cos.endText();

//Code
cos.beginText();
cos.setFont(fontMono, size_font_Code);
cos.setNonStrokingColor(Color.BLACK);
cos.moveTextPositionByAmount(offset_Code_x,offset_Code_y);
cos.drawString(barCode);
cos.endText();

bitMatrix = new Code128Writer().encode(barCode, BarcodeFormat.CODE_128, 10, margin/2, null);
BufferedImage buffImg = MatrixToImageWriter.toBufferedImage(bitMatrix);
PDXObjectImage ximage = new PDPixelMap(document, buffImg);
cos.drawXObject(ximage, 10, 5, 90, 10);

} catch (FileNotFoundException fnfex) {
System.out.println("No image for you");
}

cos.close();
PrintBrother pb = new PrintBrother();
try
{
pb.print(document, barCode);
}
catch (Exception e)
{
System.out.println(e.toString());
}
document.save(outputFileName);
document.close();
}
}
mit dem Foxit PDFReader geht das Drucken ohne Probleme...
 
Zuletzt bearbeitet:
ok, das sieht erst einmal aus meiner Sicht korrekt aus. Das, was ich da als Idee hatte, ist damit erst einmal hinfällig.
 
Rollengrösse einstellung passt. Ausrichtung habe ich auch schon probiert, bringt auch nichts 🙁
Mich stört die Anzeige 62mm x 4, eine solche rolle hab ich nicht drinnen...
Kann man irgendwo in Java noch die Mediumgrösse auswählen?
 
Zuletzt bearbeitet:
Gibt es andere Alternativen aus Java ein PDF zu drucken?
Das 62mm x 4 ist in der Auflistung der verfügbaren Papiergrössen im Druckertreiber zu finden, aber nicht ausgewählt.
 
Also der Prinerservice ist definitziv der Richtige Drucker, aber gibt's da noch Optionen, wo man die Mediengrösse auswählen kann?
 
Ich habe keine Ahnung; aber ich würde mal ausprobieren, ob es nicht mehrere Printservices gibt mit dem gleichen Druckernamen, also

Java:
public static void main(String[] args) {
    PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
    for (PrintService printService : printServices) {
        if (printService.getName().trim().equals("Brother QL-600")) {
            System.out.println(printService);
        }
    }
}
 
Nein, es gibt nur den einen. Allerdings wird Windows32 angezeigt, obwohl ich den 64 bit Treiber installiert habe...
Im Augenblick irritiert mich das etwas - Bei den Treibern unterscheidet Windws eigentlich nicht dachte ich....

Hast Du ein 64Bit Java oder nutzt Du eine 32Bit Version? Also mal ein java -version aufrufen um das zu prüfen. Solltest Du eine 32Bit Version ovn Java nutzen, dann würde ich die deinstallieren und die 64bit Version installieren. Evtl. bewirkt das dann schon etwas - auch wenn ich mir das gerade nicht vorstellen kann.
 
Gibt es andere Alternativen aus Java ein PDF zu drucken?
Das 62mm x 4 ist in der Auflistung der verfügbaren Papiergrössen im Druckertreiber zu finden, aber nicht ausgewählt.
@KonradN hatte zwar schon danach gefragt, aber irgendwie ist das untergegangen: in Deinem Code ist nicht erkennbar, dass Du irgendwo mitgeben würdest, welches Papierformat verwendet werden soll.

Ich würde mal versuchen, die Druckeinstellungen herauszufinden. Hier mal eine angepasste Version von der Oracle-Seite. Die gibt die gewählten PrintRequestAttributes aus. Evtl. kommst Du damit weiter.

Java:
/*
 * Copyright (c) 2001, 2020, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle or the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */ 

import java.io.*;
import java.awt.*;
import java.net.*;
import java.awt.image.*;
import java.awt.print.*;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;

public class Print2DPrinterJob implements Printable {

    public Print2DPrinterJob() {

        /* Construct the print request specification.
        * The print data is a Printable object.
        * the request additonally specifies a job name, 2 copies, and
        * landscape orientation of the media.
        */
        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
        aset.add(OrientationRequested.LANDSCAPE);
        aset.add(new Copies(2));
        aset.add(new JobName("My job", null));

        /* Create a print job */
        PrinterJob pj = PrinterJob.getPrinterJob();       
        pj.setPrintable(this);
        /* locate a print service that can handle the request */
        PrintService[] services =
                PrinterJob.lookupPrintServices();

        if (services.length > 0) {
            System.out.println("selected printer " + services[0].getName());
            try {
                pj.setPrintService(services[0]);
                pj.pageDialog(aset);
                System.out.println("Page settings");
                showAttributes(aset);
                if(pj.printDialog(aset)) {
                    System.out.println("Print settings");
                    showAttributes(aset);
                }
            } catch (PrinterException pe) { 
                System.err.println(pe);
            }
        }
    }

    private void showAttributes(AttributeSet set) {
        for (Attribute att : set.toArray()) {
                System.out.println(att.getName() + ": " + att.toString());
        }
    }

    public int print(Graphics g,PageFormat pf,int pageIndex) {
        if (pageIndex == 0) {
            return Printable.PAGE_EXISTS;
        }
        return Printable.NO_SUCH_PAGE;
    }

    public static void main(String arg[]) {
        Print2DPrinterJob sp = new Print2DPrinterJob();
    }
}
 
@KonradN hatte zwar schon danach gefragt, aber irgendwie ist das untergegangen: in Deinem Code ist nicht erkennbar, dass Du irgendwo mitgeben würdest, welches Papierformat verwendet werden soll.

Ich würde mal versuchen, die Druckeinstellungen herauszufinden. Hier mal eine angepasste Version von der Oracle-Seite. Die gibt die gewählten PrintRequestAttributes aus. Evtl. kommst Du damit weiter.

Java:
/*
 * Copyright (c) 2001, 2020, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle or the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.io.*;
import java.awt.*;
import java.net.*;
import java.awt.image.*;
import java.awt.print.*;
import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;

public class Print2DPrinterJob implements Printable {

    public Print2DPrinterJob() {

        /* Construct the print request specification.
        * The print data is a Printable object.
        * the request additonally specifies a job name, 2 copies, and
        * landscape orientation of the media.
        */
        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
        aset.add(OrientationRequested.LANDSCAPE);
        aset.add(new Copies(2));
        aset.add(new JobName("My job", null));

        /* Create a print job */
        PrinterJob pj = PrinterJob.getPrinterJob();      
        pj.setPrintable(this);
        /* locate a print service that can handle the request */
        PrintService[] services =
                PrinterJob.lookupPrintServices();

        if (services.length > 0) {
            System.out.println("selected printer " + services[0].getName());
            try {
                pj.setPrintService(services[0]);
                pj.pageDialog(aset);
                System.out.println("Page settings");
                showAttributes(aset);
                if(pj.printDialog(aset)) {
                    System.out.println("Print settings");
                    showAttributes(aset);
                }
            } catch (PrinterException pe) {
                System.err.println(pe);
            }
        }
    }

    private void showAttributes(AttributeSet set) {
        for (Attribute att : set.toArray()) {
                System.out.println(att.getName() + ": " + att.toString());
        }
    }

    public int print(Graphics g,PageFormat pf,int pageIndex) {
        if (pageIndex == 0) {
            return Printable.PAGE_EXISTS;
        }
        return Printable.NO_SUCH_PAGE;
    }

    public static void main(String arg[]) {
        Print2DPrinterJob sp = new Print2DPrinterJob();
    }
}
Ich denke mittlerweile, dass es ein Treiberproblem ist. Hier werden nicht alle Formate angezeigt, die in den Druckereinstellungen unter Windows angezeigt werden.
 
Nach 2 schlaflosen Nächten hab ich das problem lösen können. Kein Treiberproblem, Pageformat hab ich noch einrichten müssen:


public void print (PDDocument document, String inName) throws NullPointerException, IllegalArgumentException, PrinterException
{

PrintService printService = findPrintService("Brother QL-600");
PrinterJob job = PrinterJob.getPrinterJob();

PageFormat pf = job.defaultPage();
Paper paper = new Paper();
paper.setSize(paper_width_mm*MM_TO_POINT, paper_height_mm*MM_TO_POINT);
double margin = 0;
paper.setImageableArea(margin, margin, paper.getWidth() - margin, paper.getHeight() - margin);
pf.setPaper(paper);
pf.setOrientation(PageFormat.PORTRAIT);
//job.validatePage(pf);
Book pageable = new Book ();
pageable.append(document.getPrintable(0), pf);
job.setPrintService(printService);
job.setJobName(inName);
job.setCopies(2);
//job.setPageable(new PDPageable(document,job));
job.setPageable(pageable);

job.print();

}
 

Neue Themen


Zurück
Oben