gpt4 book ai didi

android - 在android中打印现有的pdf文件

转载 作者:太空宇宙 更新时间:2023-11-03 11:36:54 28 4
gpt4 key购买 nike

大家好,我正在尝试在 Android 上构建一个小型示例打印应用程序,但似乎无法打印现有的 pdf。有很多关于使用 Canvas 创建自定义文档的文档,但我已经有了该文档。基本上我只想能够读取 pdf 文档并将其作为文件输出流直接发送到要打印的打印机。感谢您的帮助。

最佳答案

我们可以通过创建自定义 PrintDocumentAdapter 来简单地实现这一点

PdfDocumentAdapter.java

public class PdfDocumentAdapter extends PrintDocumentAdapter {

Context context = null;
String pathName = "";
public PdfDocumentAdapter(Context ctxt, String pathName) {
context = ctxt;
this.pathName = pathName;
}
@Override
public void onLayout(PrintAttributes printAttributes, PrintAttributes printAttributes1, CancellationSignal cancellationSignal, LayoutResultCallback layoutResultCallback, Bundle bundle) {
if (cancellationSignal.isCanceled()) {
layoutResultCallback.onLayoutCancelled();
}
else {
PrintDocumentInfo.Builder builder=
new PrintDocumentInfo.Builder(" file name");
builder.setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
.setPageCount(PrintDocumentInfo.PAGE_COUNT_UNKNOWN)
.build();
layoutResultCallback.onLayoutFinished(builder.build(),
!printAttributes1.equals(printAttributes));
}
}

@Override
public void onWrite(PageRange[] pageRanges, ParcelFileDescriptor parcelFileDescriptor, CancellationSignal cancellationSignal, WriteResultCallback writeResultCallback) {
InputStream in=null;
OutputStream out=null;
try {
File file = new File(pathName);
in = new FileInputStream(file);
out=new FileOutputStream(parcelFileDescriptor.getFileDescriptor());

byte[] buf=new byte[16384];
int size;

while ((size=in.read(buf)) >= 0
&& !cancellationSignal.isCanceled()) {
out.write(buf, 0, size);
}

if (cancellationSignal.isCanceled()) {
writeResultCallback.onWriteCancelled();
}
else {
writeResultCallback.onWriteFinished(new PageRange[] { PageRange.ALL_PAGES });
}
}
catch (Exception e) {
writeResultCallback.onWriteFailed(e.getMessage());
Logger.logError( e);
}
finally {
try {
in.close();
out.close();
}
catch (IOException e) {
Logger.logError( e);
}
}
}}

现在使用PrintManager调用打印

        PrintManager printManager=(PrintManager) getActivityContext().getSystemService(Context.PRINT_SERVICE);
try
{
PrintDocumentAdapter printAdapter = new PdfDocumentAdapter(Settings.sharedPref.context,filePath );
}
printManager.print("Document", printAdapter,new PrintAttributes.Builder().build());
}
catch (Exception e)
{
Logger.logError(e);
}

关于android - 在android中打印现有的pdf文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33089808/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com