我正在编写专有的PrintService
,并且在接收到的由Android PrintManager
生成的PDF文件时遇到一些问题。
我想某些打印属性设置不正确。
这是我用来打印内容的简单代码。这是我的测试应用程序:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = new WebView(this);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
// I also set padding to 0 in case....
webView.setPadding(0, 0, 0, 0);
// So I tried to set html margin/padding to 0 but it doesn't change the print preview
String summary = "<html><body style=\"margin: 0; padding: 0; width:100%; height: 100%;\">" +
"-------------------------------------<br/>" +
"I'm just printing something!<br/>" +
"-------------------------------------<br/>" +
"</body></html>";
webView.loadData(summary, "text/html; charset=utf-8", "utf-8");
}
public void createWebPrintJob(View view) {
PrintManager printManager = (PrintManager) this
.getSystemService(Context.PRINT_SERVICE);
if (printManager != null) {
String jobName = getString(R.string.app_name);
PrintJob job = null;
PrintDocumentAdapter printAdapter =
webView.createPrintDocumentAdapter(jobName);
if ((job = (printManager.print(jobName, printAdapter,
new PrintAttributes.Builder().build()))) != null) {
Toast.makeText(this, "Job succesfully created", Toast.LENGTH_SHORT).show();
}
}
}
现在,在
PrintService
端,下面是我如何初始化打印机功能:@Override
public void onStartPrinterStateTracking(@NonNull PrinterId printerId) {
Log.d(TAG, "onStartPrinterStateTracking");
PrinterInfo printer = findPrinterInfo(printerId);
if (printer != null) {
PrintAttributes.MediaSize rollSize = new PrintAttributes.MediaSize("Roll58mm", "Roll58mm", 1892, 5676);
PrintAttributes.Margins rollMargins = new PrintAttributes.Margins(0, 0, 0, 0);
PrinterCapabilitiesInfo capabilities = new PrinterCapabilitiesInfo.Builder(printerId)
.addMediaSize(rollSize, true)
.setColorModes(PrintAttributes.COLOR_MODE_MONOCHROME, PrintAttributes.COLOR_MODE_MONOCHROME)
.addResolution(new PrintAttributes.Resolution("200dpi", "paperRoll", 203,203), true)
.setMinMargins(rollMargins)
.build();
printer = new PrinterInfo.Builder(printer)
.setCapabilities(capabilities)
.build();
List<PrinterInfo> printers = new Vector<>();
printers.add(printer);
addPrinters(printers);
} else {
Log.e(TAG, "Unable to find requested printer !");
}
}
这是打印预览,因此我不明白为什么在文字周围出现边距或填充,而我为所有文字都指定了0。
那么为什么我在这里为所有指定0时看到边距?
-编辑-
我已经根据一些谈论类似问题的文章更新了我的
onCreate
方法,但没有成功! 最佳答案
我通过在HTML中添加CSS样式来解决此问题。
<style type="text/css" media="print">
@page
{
size: auto; /* auto is the initial value */
margin: 0mm; /* this affects the margin in the printer settings */
}
html
{
background-color: #FFFFFF;
margin: 0px; /* this affects the margin on the html before sending to printer */
}
body
{
margin: 0mm; /* margin you want for the content */
}
</style>