【问题标题】:I want to print automatically without user interaction我想在没有用户交互的情况下自动打印
【发布时间】:2019-12-18 17:42:10
【问题描述】:

当用户点击 UI 中的按钮时,PrintManager 会生成要打印的 Document。然后用户点击打印图标推送打印命令。

以上部分已经完成。 但要求是: 我想删除用户必须单击打印图标(图中显示的打印图标,由 PrintDocumentAdapter 生成)并自动生成/打印文档。

再次: 我已经实现了打印功能,我只想删除用户交互。当生成下图时,打印命令会自动执行,无需用户点击打印图标。

【问题讨论】:

    标签: android


    【解决方案1】:

    不要使用 PrintManager,您可以使用 android.print 包中的 PdfPrint.java 类进行打印。

    将此代码放在 java/android/print 中(在您的包之外)

    package android.print;
    
    import android.os.CancellationSignal;
    import android.os.ParcelFileDescriptor;
    import android.util.Log;
    
    import java.io.File;
    
    public class PdfPrint {
    
        private static final String TAG = PdfPrint.class.getSimpleName();
        private final PrintAttributes printAttributes;
    
        public PdfPrint(PrintAttributes printAttributes) {
            this.printAttributes = printAttributes;
        }
    
        public void print(final PrintDocumentAdapter printAdapter, final File path, final String fileName) {
            printAdapter.onLayout(null, printAttributes, null, new PrintDocumentAdapter.LayoutResultCallback() {
                @Override
                public void onLayoutFinished(PrintDocumentInfo info, boolean changed) {
                    printAdapter.onWrite(new PageRange[]{PageRange.ALL_PAGES}, getOutputFile(path, fileName), new CancellationSignal(), new PrintDocumentAdapter.WriteResultCallback() {
                        @Override
                        public void onWriteFinished(PageRange[] pages) {
                            super.onWriteFinished(pages);
                        }
                    });
                }
            }, null);
        }
    
        private ParcelFileDescriptor getOutputFile(File path, String fileName) {
            if (!path.exists()) {
                path.mkdirs();
            }
            File file = new File(path, fileName);
            try {
                file.createNewFile();
                return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_WRITE);
            } catch (Exception e) {
                Log.e(TAG, "Failed to open ParcelFileDescriptor", e);
            }
            return null;
        }
    }
    

    你可以使用这样的代码(从 webview 打印)

    private fun createWebPrintJob(webView: WebView, date: Long) {
            try {
                val jobName = getString(R.string.app_name) + " Document"
                val attributes = PrintAttributes.Builder()
                    .setMediaSize(PrintAttributes.MediaSize.NA_LEGAL)
                    .setResolution(PrintAttributes.Resolution("pdf", "pdf", 600, 600))
                    .setMinMargins(PrintAttributes.Margins.NO_MARGINS).build()
                val path =
                    Environment.getExternalStoragePublicDirectory("/pdf_output")
    
                val pdfPrint = PdfPrint(attributes)
                pdfPrint.print(
                    webView.createPrintDocumentAdapter(jobName),
                    path,
                    "output_$date.pdf"
                )
                Log.i("pdf", "pdf created")
            } catch (e: Exception) {
                Log.e("pdf", " pdf failed e.localizedMessage")
            }
        }
    

    【讨论】:

    • 我创建了 pdf,但没有打印出来
    【解决方案2】:

    你可以试试这个:

     private void doPhotoPrint() {
    
            if (imageLoader == null) {
                imageLoader = new GlideImageLoader(this);
            }
    
            if (!IMG_PATH.isEmpty()) {
    
                imageLoader.bindImageAsBitmap(null, FileUtils.validateFileUrl(IMG_PATH), new RequestListener<Bitmap>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) {
                        return false;
                    }
    
                    @Override
                    public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) {
                        return false;
                    }
                }, new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        Activity activity = ShareImgActivity.this;
                        if (resource != null && AppUtils.isValidContext(activity)) {
                            PrintHelper photoPrinter = new PrintHelper(activity);
                            photoPrinter.setScaleMode(PrintHelper.SCALE_MODE_FIT);
                            photoPrinter.printBitmap(getString(R.string.app_name) + "_Print", resource);
                        }
                    }
                }, Priority.IMMEDIATE);
            }
        }
    

    【讨论】:

      【解决方案3】:

      对于 PrintManager 的实现,你可以看看下面的代码行:

      来源: https://developer.android.com/training/printing/custom-docs.html

      private void doPrint() {
          // Get a PrintManager instance
          PrintManager printManager = (PrintManager) getActivity()
                  .getSystemService(Context.PRINT_SERVICE);
      
          // Set job name, which will be displayed in the print queue
          String jobName = getActivity().getString(R.string.app_name) + " Document";
      
          // Start a print job, passing in a PrintDocumentAdapter implementation
          // to handle the generation of a print document
          printManager.print(jobName, new MyPrintDocumentAdapter(getActivity()),
                  null); //
      }
      

      【讨论】:

      • 这一切我都做了。你读过我写的问题吗,上面的部分已经完成了。
      • 好的很好,是的,我没看到。那么您是否尝试实现“自定义文档打印”,您可以绕过点击“默认打印图标”按钮?
      • @karticchaudhary 请查看以下“自定义文档打印”链接并检查它是否对您的要求有用:techotopia.com/index.php/…
      猜你喜欢
      • 2011-11-28
      • 1970-01-01
      • 2014-11-17
      • 1970-01-01
      • 1970-01-01
      • 2016-12-24
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      相关资源
      最近更新 更多