我在标签打印机上打印时遇到了问题。下面的代码在一个上打印4个“标签”(附标签图片)。
下面的代码打印到兄弟QL-500标签打印机上。它打印到3.5"乘1.1"标签上。
如果有人能帮我更好地理解代码,那也太好了。
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import javax.print.PrintService;
public class DYMOLabelPrintConnector implements Printable {
public static final String PRINTERNAME = "DYMO LabelWriter 400";
public static final boolean PRINTMENU = false;
public static void main(String[] args) {
PrinterJob printerJob = PrinterJob.getPrinterJob();
PageFormat pageFormat = printerJob.defaultPage();
Paper paper = new Paper();
final double widthPaper = (1.2 * 72);
final double heightPaper = (1.5 * 72);
paper.setSize(widthPaper, heightPaper);
paper.setImageableArea(0, 0, widthPaper, heightPaper);
pageFormat.setPaper(paper);
pageFormat.setOrientation(PageFormat.LANDSCAPE);
if (PRINTMENU) {
if (printerJob.printDialog()) {
printerJob.setPrintable(new DYMOLabelPrintConnector(), pageFormat);
try {
printerJob.print();
} catch (PrinterException e) {
e.printStackTrace();
}
}
} else {
PrintService[] printService = PrinterJob.lookupPrintServices();
for (int i = 0; i < printService.length; i++) {
System.out.println(printService[i].getName());
if (printService[i].getName().compareTo(PRINTERNAME) == 0) {
try {
printerJob.setPrintService(printService[i]);
printerJob.setPrintable(new DYMOLabelPrintConnector(), pageFormat);
printerJob.print();
} catch (PrinterException e) {
e.printStackTrace();
}
}
}
}
System.exit(0);
}
public String getValue(final int elementOnLabel, final int labelCounter) {
String value = "";
switch (elementOnLabel) {
case 0:
// what ever you want to have in this line
value = "SetupX";
break;
case 1:
// what ever you want to have in this line
value = "fiehnlab.ucd";
break;
case 2:
// what ever you want to have in this line
value = "id: " + labelCounter;
break;
case 3:
// what ever you want to have in this line
// TODO - add DB connection
value = "label:" + elementOnLabel;
break;
case 4:
// what ever you want to have in this line
value = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US).format(new Date());
break;
default:
break;
}
return value;
}
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
throws PrinterException {
System.out.println("printing page: " + pageIndex);
if (pageIndex < getPageNumbers()) {
Graphics2D g = (Graphics2D) graphics;
// g.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
g.translate(20, 10);
String value = "";
pageIndex = pageIndex + 1;
// specific for four circular labels per page
for (int x = 0; x < 80; x = x + 50) {
for (int y = 0; y < 80; y = y + 36) {
int posOnPage = 4; // BottomRight, TopRight, BottomLeft, TopLeft
if (x > 0) {
posOnPage = posOnPage - 2;
}
if (y > 0) {
posOnPage = posOnPage - 1;
}
// current counter for the label.
int id = (posOnPage - 1) + ((pageIndex - 1) * 4);
// setupx
g.setFont(new Font(g.getFont().getFontName(), g.getFont().getStyle(), 3));
value = this.getValue(0, id);
g.drawString(" " + value, x, y);
// fiehnlab
g.setFont(new Font(g.getFont().getFontName(), g.getFont().getStyle(), 3));
value = this.getValue(1, id);
g.drawString(" " + value, x, y + 4);
// ID
g.setFont(new Font(g.getFont().getFontName(), Font.BOLD, 7));
value = this.getValue(2, id);
g.drawString("" + value, x, y + 10);
// label
g.setFont(new Font(g.getFont().getFontName(), g.getFont().getStyle(), 5));
value = this.getValue(3, id);
g.drawString(" " + value, x, y + 16);
// date
g.setFont(new Font(g.getFont().getFontName(), Font.PLAIN, 3));
value = this.getValue(4, id);
g.drawString(" " + value, x, y + 20);
}
}
return PAGE_EXISTS;
} else {
return NO_SUCH_PAGE;
}
}
public int getPageNumbers() {
return 5;
}
}
enter code here
下面是它打印的内容:
我有一个类似的代码,但无法使东芝便携式打印机在TPCL模式下打印,我的代码工作正常,但只有当打印机在ESC/POS模式下。我的打印机是东芝B-EP4-DL
这是我的主要活动:
package com.example.warehousev3;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.mazenrashed.printooth.Printooth;
import com.mazenrashed.printooth.data.printable.Printable;
import com.mazenrashed.printooth.data.printable.RawPrintable;
import com.mazenrashed.printooth.data.printable.TextPrintable;
import com.mazenrashed.printooth.data.printer.DefaultPrinter;
import com.mazenrashed.printooth.ui.ScanningActivity;
import com.mazenrashed.printooth.utilities.Printing;
import com.mazenrashed.printooth.utilities.PrintingCallback;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements PrintingCallback {
DatabaseHelper myDb;
Button btnPrint, btn_unpair_pair;
EditText barcodefield = null;
Printing printing;
private Calendar calendar;
private SimpleDateFormat dateFormat;
private String date;
private final static char ESC_CHAR = 0x1B; // to be used on esc/pos commands
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calendar = Calendar.getInstance();
dateFormat = new SimpleDateFormat("dd/MM/yyyy");
date = dateFormat.format(calendar.getTime());
myDb = new DatabaseHelper(this);
btnPrint = findViewById(R.id.cmd_print);
barcodefield = findViewById(R.id.txt_barcode);
btn_unpair_pair = findViewById(R.id.btnPiarUnpair);
btnPrint.setVisibility(View.GONE); //Set Print Button Invisible
viewAll();
}
public void viewAll() {
if (printing != null)
printing.setPrintingCallback(this);
btn_unpair_pair.setOnClickListener(view -> {
if (Printooth.INSTANCE.hasPairedPrinter())
Printooth.INSTANCE.removeCurrentPrinter();
else {
startActivityForResult(new Intent(MainActivity.this, ScanningActivity.class), ScanningActivity.SCANNING_FOR_PRINTER);
changePairAndUpair();
}
});
/* //Print Button function
btnPrint.setOnClickListener(view -> {
if (!Printooth.INSTANCE.hasPairedPrinter())
startActivityForResult(new Intent(MainActivity.this,
ScanningActivity.class), ScanningActivity.SCANNING_FOR_PRINTER);
else
printText();
barcodefield.setText("");
});
*/
barcodefield.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
for (int i = 0; i < s.length(); i++) {
if(barcodefield.getText().toString().length() == 13) {
if (!Printooth.INSTANCE.hasPairedPrinter())
startActivityForResult(new Intent(MainActivity.this, ScanningActivity.class), ScanningActivity.SCANNING_FOR_PRINTER);
else
printText();
barcodefield.setText("");
}
}
}
});
changePairAndUpair();
}
private void changePairAndUpair() {
if (Printooth.INSTANCE.hasPairedPrinter())
btn_unpair_pair.setText(new StringBuilder("Unpair
").append(Printooth.INSTANCE.getPairedPrinter().getName()).toString());
else
btn_unpair_pair.setText("Pair with Printer");
}
@Override
public void connectingWithPrinter() {
Toast.makeText(this, "Connectiong to printer", Toast.LENGTH_SHORT).show();
}
@Override
public void connectionFailed(String s) {
Toast.makeText(this, "Failed: "+s, Toast.LENGTH_SHORT).show();
}
@Override
public void onError(String s) {
Toast.makeText(this, "Error: "+s, Toast.LENGTH_SHORT).show();
}
@Override
public void onMessage(String s) {
Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
}
@Override
public void printingOrderSentSuccessfully() {
Toast.makeText(this, "Order sent to printer", Toast.LENGTH_SHORT).show();
}
private void printText() {
ArrayList<Printable> printables = new ArrayList<>();
printables.add(new RawPrintable.Builder(new byte[]{27, 100, 4}).build());
//Original Code
//printables.add(new RawPrintable.Builder(new byte[]{0x1B,'d', 5}).build()); //
FEED 5 LINES WORKING!!!!!!!!
//printables.add(new RawPrintable.Builder(new byte[]{'L','H', 0x56}).build()); //
FEED 10 LINES WORKING!!!!!!!!
//printables.add(new RawPrintable.Builder(new byte[]{}).build()); // lane for
test
myDb.setBarcodcheck(String.valueOf(barcodefield.getText()));
Cursor res = myDb.getAllData();
if (res.getCount() == 0) {
showMessage("Error", "Nothing Found");
return;
}
StringBuffer buffer = new StringBuffer();
while (res.moveToNext()) {
buffer.append(res.getString(0)+"\n");
buffer.append(res.getString(1)+"\n");
buffer.append(res.getString(2)+"\n");
buffer.append(date+"\n");
buffer.append("\n");
}
printables.add(new TextPrintable.Builder()
.setText(buffer.toString()) // Original code
//.setText(String.valueOf(buffer))
.setCharacterCode(DefaultPrinter.Companion.getCHARCODE_PC1252())
.setLineSpacing(DefaultPrinter.Companion.getLINE_SPACING_60())
.setEmphasizedMode(DefaultPrinter.Companion.getEMPHASIZED_MODE_BOLD())
.setFontSize(DefaultPrinter.Companion.getFONT_SIZE_LARGE())
//.setNewLinesAfter(1)
.build());
//printables.add(new RawPrintable.Builder(new byte[]{0x1B,'d', 5}).build()); // FEED 5 LINES WORKING!!!!!!!!
//printables.add(new RawPrintable.Builder(new byte[]{}).build()); // Line for test
Printooth.INSTANCE.printer().print(printables);
}
public void showMessage(String title, String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent
data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ScanningActivity.SCANNING_FOR_PRINTER && resultCode ==
Activity.RESULT_OK)
initPrinting();
changePairAndUpair();
}
private void initPrinting() {
if (!Printooth.INSTANCE.hasPairedPrinter())
printing = Printooth.INSTANCE.printer();
if (printing != null)
printing.setPrintingCallback(this);
}
}
#After a long hour of analysis found 100% solution
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBody;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTDocument1;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPageMar;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPageSz;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STPageOrientation;
public class CreateWord {
public static void main(String[] args) throws FileNotFoundException, IOException {
XWPFDocument doc = new XWPFDocument();
CTDocument1 document = doc.getDocument();
CTBody body = document.getBody();
if (!body.isSetSectPr()) {
body.addNewSectPr();
}
CTSectPr section = body.getSectPr();
if (!section.isSetPgSz()) {
section.addNewPgSz();
}
if (!section.isSetPgMar()) {
CTPageMar margin = section.addNewPgMar();
margin.setTop(BigInteger.valueOf(500));
margin.setBottom(BigInteger.valueOf(100));
margin.setLeft(BigInteger.valueOf(0));
margin.setRight(BigInteger.valueOf(0));
}
CTPageSz pageSize = section.getPgSz();
pageSize.setOrient(STPageOrientation.LANDSCAPE);
pageSize.setW(BigInteger.valueOf(6000));
pageSize.setH(BigInteger.valueOf(2000));
XWPFParagraph title = doc.createParagraph();
XWPFRun run = title.createRun();
// run.setText("Fig.1 A Natural Scene");
// run.setBold(true);
// title.setAlignment(ParagraphAlignment.CENTER);
String imgFile = "E:\\barcode.png";
FileInputStream is = new FileInputStream(imgFile);
// run.addBreak();
try {
run.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, imgFile, Units.toEMU(300), Units.toEMU(70));
} catch (InvalidFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // 200x200
// pixels
is.close();
FileOutputStream fos = new FileOutputStream("E:\\test4.docx");
doc.write(fos);
fos.close();
}
}
[1]: https://i.stack.imgur.com/VA0IL.png
[2]: https://i.stack.imgur.com/9aSv4.png
哇,我不能告诉你我有多喜欢用Java打印,当它工作时,它很棒......
.
public class PrinterTest {
public static void main(String[] args) {
PrinterJob pj = PrinterJob.getPrinterJob();
if (pj.printDialog()) {
PageFormat pf = pj.defaultPage();
Paper paper = pf.getPaper();
double width = fromCMToPPI(3.5);
double height = fromCMToPPI(8.8);
paper.setSize(width, height);
paper.setImageableArea(
fromCMToPPI(0.25),
fromCMToPPI(0.5),
width - fromCMToPPI(0.35),
height - fromCMToPPI(1));
System.out.println("Before- " + dump(paper));
pf.setOrientation(PageFormat.PORTRAIT);
pf.setPaper(paper);
System.out.println("After- " + dump(paper));
System.out.println("After- " + dump(pf));
dump(pf);
PageFormat validatePage = pj.validatePage(pf);
System.out.println("Valid- " + dump(validatePage));
//Book book = new Book();
//book.append(new MyPrintable(), pf);
//pj.setPageable(book);
pj.setPrintable(new MyPrintable(), pf);
try {
pj.print();
} catch (PrinterException ex) {
ex.printStackTrace();
}
}
}
protected static double fromCMToPPI(double cm) {
return toPPI(cm * 0.393700787);
}
protected static double toPPI(double inch) {
return inch * 72d;
}
protected static String dump(Paper paper) {
StringBuilder sb = new StringBuilder(64);
sb.append(paper.getWidth()).append("x").append(paper.getHeight())
.append("/").append(paper.getImageableX()).append("x").
append(paper.getImageableY()).append(" - ").append(paper
.getImageableWidth()).append("x").append(paper.getImageableHeight());
return sb.toString();
}
protected static String dump(PageFormat pf) {
Paper paper = pf.getPaper();
return dump(paper);
}
public static class MyPrintable implements Printable {
@Override
public int print(Graphics graphics, PageFormat pageFormat,
int pageIndex) throws PrinterException {
System.out.println(pageIndex);
int result = NO_SUCH_PAGE;
if (pageIndex < 2) {
Graphics2D g2d = (Graphics2D) graphics;
System.out.println("[Print] " + dump(pageFormat));
double width = pageFormat.getImageableWidth();
double height = pageFormat.getImageableHeight();
g2d.translate((int) pageFormat.getImageableX(),
(int) pageFormat.getImageableY());
g2d.draw(new Rectangle2D.Double(1, 1, width - 1, height - 1));
FontMetrics fm = g2d.getFontMetrics();
g2d.drawString("0x0", 0, fm.getAscent());
result = PAGE_EXISTS;
}
return result;
}
}
}
如果你试着指定纸张大小和页边距,我意识到PrintDialog有一些不一致的地方,但老实说,这是另一个问题。
我发布的代码能够在我的Dymo LabelWriter 400 Turbo上一个接一个地打印两个标签,没有问题。
更新还应该提到,我认为你基本上错过了PageFormat.setPaper
更新了烧烤条形码
从文件示例打印…
Barcode b = BarcodeFactory.createCode128("Hello");
b.setResolution(72);
File f = new File("mybarcode.png");
// Let the barcode image handler do the hard work
BarcodeImageHandler.savePNG(b, f);
.
.
.
public static class PrintFromFile implements Printable {
@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
int result = NO_SUCH_PAGE;
if (pageIndex == 0) {
graphics.translate((int)pageFormat.getImageableX(), (int)pageFormat.getImageableY());
result = PAGE_EXISTS;
try {
// You may want to rescale the image to better fit the label??
BufferedImage read = ImageIO.read(new File("mybarcode.png"));
graphics.drawImage(read, 0, 0, null);
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
直接打印到图形上下文
Barcode b = BarcodeFactory.createCode128("Hello");
b.setResolution(72);
.
.
.
public static class PrintToGraphics implements Printable {
private Barcode b;
private PrintToGraphics(Barcode b) {
this.b = b;
}
@Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
int result = NO_SUCH_PAGE;
if (pageIndex == 0) {
result = PAGE_EXISTS;
int x = (int)pageFormat.getImageableX();
int y = (int)pageFormat.getImageableY();
int width = (int)pageFormat.getImageableWidth();
int height = (int)pageFormat.getImageableHeight();
graphics.translate(x, y);
try {
b.draw((Graphics2D)graphics, 0, 0);
} catch (OutputException ex) {
ex.printStackTrace();
}
}
return result;
}
}
最后但并非最不重要的一点是,直接从“示例”目录下载
public class PrintingExample
{
public static void main(String[] args)
{
try
{
Barcode b = BarcodeFactory.createCode128("Hello");
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(b);
if (job.printDialog())
{
job.print();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
我想从web浏览器的Brother标签打印机打印标签。我知道DYMO有一个JavaScript框架,可以使从浏览器打印变得简单。但我有一个兄弟标签打印机的客户,所以我需要使它工作。 我一直在做一些测试和搜索,令人惊讶的是,关于这个主题的信息如此之少。 到目前为止,我唯一成功使用的浏览器是谷歌Chrome,因为它似乎不打印页眉和页脚。我已经安装了打印机/驱动程序,并创建了尺寸为62 x 29mm的自
我有打印机驱动程序、P-touch编辑器、b-PAC 3.1和客户端工具,都是64位的,从Brother网站下载并安装在我的64位Windows 7笔记本电脑上。P-touch编辑器工作/打印良好。 然而,b-PAC失败,所有样本均无效。我调试了代码: 其中,
问题内容: Java中有一种简单的方法可以执行以下操作吗? 连接到打印机(将是本地打印机,并且是连接到机器的唯一打印机)。 在2个不同的打印机纸盘中打印2页的页面。 获取当前的打印队列计数,即我有100项要打印的项目和34项当前已打印,则打印机队列现在应显示为66。 问题答案: 一些快速提示: 从Java打印:请参阅基本打印程序 打印作业的状态:您可以使用PrintJobListener获得一些有
我需要发送一个pdf文件打印在一个网络应用程序的服务器端,打印机完全支持pdf打印等,它是网络以及服务器。pdf也存储在服务器上。 我尝试的是点击一个按钮,打印出pdf文件,目前我有以下代码: 但我有几个问题,我如何将pdf放入输入流以打印出来,我可以选择诸如双面打印之类的选项,以及如何从JSF web应用程序中调用它 谢谢
问题内容: 我已经将内存中的Postscript代码/数据(?)(在Java Tomcat webapp中)直接发送到联网的PS打印机。有没有一种简单的方法(即只是弹出一个端口并发送文本)来打印此内容,而绕过所有特定于O / S的驱动程序和内容(并希望甚至不需要额外的jar)?示例代码的链接显示了如何执行此操作? 谢谢戴夫 问题答案: 在目标打印机的LPR端口上打开一个TCP套接字。 发送您的数据
我们希望打印到连接在apache运行的POS打印机上。由于应用程序的设计和部署,打印应该从服务器上完成(它应该检测订单并发送到不同的打印机和不同格式的打印...账单,厨房订单,等等...)。出于这个原因和其他原因(例如,从iPad访问应用程序),我们放弃了像QZ-Print applet这样的选项,并需要直接在服务器端打印。 提前谢了。