java - E/PdfManipulationService : Cannot open file java. io.IOException : not create document. 错误:

标签 java android printing

大家好,我正在开发文档打印应用程序,首先我使用iTextlib创建一个pdf文件,然后我通过IP地址连接打印机,一切进展顺利,但是当我打印(hp打印机)文档时,我收到了错误

类似下面的错误

 E/PdfManipulationService: Cannot open file
 java.io.IOException: not create document. Error:
 at android.graphics.pdf.PdfRenderer.nativeCreate(Native Method)
 at android.graphics.pdf.PdfRenderer.<init>(PdfRenderer.java:153)
 at com.android.printspooler.renderer.PdfManipulationService$PdfRendererImpl.openDocument(PdfManipulationService.java:92)
 at com.android.printspooler.renderer.IPdfRenderer$Stub.onTransact(IPdfRenderer.java:58)
 at android.os.Binder.execTransact(Binder.java:446)

我的代码是

主要 Activity

public class MainActivity extends AppCompatActivity {

private Button scan_Button;

private Handler mHandler;
private String ipAddress = "192.168.1.101";
PrintedPdfDocument mPdfDocument;
private int printItemCount;
private Appendable writtenPagesArray;
private int totalPages = 0;
String FILE;
String fileName = new SimpleDateFormat("yyyyMMdd_hhmmss", Locale.getDefault()).format(new Date());

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    createPdfDocument();
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    scan_Button = (Button) findViewById(R.id.scan_Button);
    scan_Button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new MakeConnection().execute();
            doPrint();
        }
    });
}

private void createPdfDocument() {


     FILE = Environment.getExternalStorageDirectory().toString()
            + "/PDF/" + fileName+".pdf";
    Log.e("FILE", "=====>"+FILE);

    // Create New Blank Document
    Document document = new Document(PageSize.A4);

    // Create Directory in External Storage
    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/PDF");
    myDir.mkdirs();
    Log.e("myDir", "=====>"+myDir);

    try {
        PdfWriter.getInstance(document, new FileOutputStream(FILE));

        // Open Document for Writting into document
        document.open();

        // User Define Method
        addMetaData(document);
        addTitlePage(document);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    // Close Document after writting all content
    document.close();

    Toast.makeText(this, "PDF File is Created. Location : " + FILE,
            Toast.LENGTH_LONG).show();
}

// Set PDF document Properties
public void addMetaData(Document document)

{
    document.addTitle("RESUME");
    document.addSubject("Person Info");
    document.addKeywords("Personal, Education, Skills");
    document.addAuthor("TAG");
    document.addCreator("TAG");
}

public void addTitlePage(Document document) throws DocumentException {
    // Font Style for Document
    Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
    Font titleFont = new Font(Font.FontFamily.TIMES_ROMAN, 22, Font.BOLD
            | Font.UNDERLINE, BaseColor.GRAY);
    Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
    Font normal = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL);

    // Start New Paragraph
    Paragraph prHead = new Paragraph();
    // Set Font in this Paragraph
    prHead.setFont(titleFont);
    // Add item into Paragraph
    prHead.add("RESUME – Amit Basliyal\n");

    // Create Table into Document with 1 Row
    PdfPTable myTable = new PdfPTable(1);
    // 100.0f mean width of table is same as Document size
    myTable.setWidthPercentage(100.0f);

    // Create New Cell into Table
    PdfPCell myCell = new PdfPCell(new Paragraph(""));
    myCell.setBorder(Rectangle.BOTTOM);

    // Add Cell into Table
    myTable.addCell(myCell);

    prHead.setFont(catFont);
    prHead.add("\n testing\n");
    prHead.setAlignment(Element.ALIGN_CENTER);

    // Add all above details into Document
    document.add(prHead);
    document.add(myTable);

    document.add(myTable);

    // Now Start another New Paragraph
    Paragraph prPersinalInfo = new Paragraph();
    prPersinalInfo.setFont(smallBold);
    prPersinalInfo.add("Address 1\n");
    prPersinalInfo.add("Address 1\n");
    prPersinalInfo.add("City: uuuu State: uuu\n");
    prPersinalInfo.add("Country: INDIA Zip Code: 000001\n");
    prPersinalInfo
            .add("Mobile: 0099999999Fax: 0101020101 Email: text@gmail.com \n");

    prPersinalInfo.setAlignment(Element.ALIGN_CENTER);

    document.add(prPersinalInfo);
    document.add(myTable);

    document.add(myTable);

    Paragraph prProfile = new Paragraph();
    prProfile.setFont(smallBold);
    prProfile.add("\n \n Profile : \n ");
    prProfile.setFont(normal);
    prProfile
            .add("\nI am Mr. XYZ. I am Android Application Developer at TAG.");

    prProfile.setFont(smallBold);
    document.add(prProfile);

    // Create new Page in PDF
    document.newPage();
}

class MakeConnection extends AsyncTask<String, Void, String> {
    String check = "NO";

    @Override
    protected String doInBackground(String... params) {
        Log.e("DoInBackGround", "==>");
        try {
            Socket sock = new Socket(ipAddress, 9100);
            PrintWriter oStream = new PrintWriter(sock.getOutputStream());
            oStream.println("HI,test from Android Device");
            oStream.println("\n\n\n\f");
            oStream.close();
            sock.close();
       // doPrint();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        Log.e("onPostExecute", "==>");
        //Logger.LogError(TAG, check);
        Log.e("onPostExecute", "==>" + check);
        //doPrint();
        super.onPostExecute(s);
    }
}


private void doPrint() {
    // Get a PrintManager instance
    PrintManager printManager = (PrintManager) this.getSystemService(Context.PRINT_SERVICE);

    // Set job name, which will be displayed in the print queue
    String jobName = this.FILE;
  //  Preferences.writeString(MainActivity.this,"filename",FILE);
    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("filename", FILE);
    editor.apply();

    // Start a print job, passing in a PrintDocumentAdapter implementation
    // to handle the generation of a print document
    printManager.print(jobName, new MyPrintDocumentAdapter(this),
            null);
   }
 }

MyPrintDocumentAdapter.java

public class MyPrintDocumentAdapter extends PrintDocumentAdapter {

Activity activity;
PrintedPdfDocument mPdfDocument;
//Page[] writtenPagesArray;

public MyPrintDocumentAdapter(Activity activity)
{
    this.activity = activity;
}

@Override
public void onLayout(PrintAttributes oldAttributes,
                     PrintAttributes newAttributes,
                     CancellationSignal cancellationSignal,
                     LayoutResultCallback callback, Bundle extras) {

    // Create a new PdfDocument with the requested page attributes
    mPdfDocument = new PrintedPdfDocument(activity, newAttributes);

    // Respond to cancellation request
    if (cancellationSignal.isCanceled() ) {
        callback.onLayoutCancelled();
        return;
    }

    // Compute the expected number of printed pages
    int pages = computePageCount(newAttributes);
    //  filename =Preferences.readString(context,"filename","");
    SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(activity);
    String name = sharedPreferences.getString("filename", "default value");
    if (pages > 0) {
        // Return print information to print framework
        PrintDocumentInfo info = new PrintDocumentInfo
              // .Builder("print_output.pdf")
                .Builder(name)
                .setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT)
                .setPageCount(pages)
                .build();
        // Content layout reflow is complete
        callback.onLayoutFinished(info, true);
    } else {
        // Otherwise report an error to the print framework
        callback.onLayoutFailed("Page count calculation failed.");
    }
}

@Override
public void onWrite(PageRange[] pages, ParcelFileDescriptor destination,
                    CancellationSignal cancellationSignal, WriteResultCallback callback) {
    // TODO Auto-generated method stub


    // Write PDF document to file
    try {
        mPdfDocument.writeTo(new FileOutputStream(
                destination.getFileDescriptor()));
    } catch (IOException e) {
        callback.onWriteFailed(e.toString());
        return;
    } finally {
        mPdfDocument.close();
        mPdfDocument = null;
    }
    //PageRange[] writtenPages = computeWrittenPages();
    // Signal the print framework the document is complete
    callback.onWriteFinished(pages);


}

private int computePageCount(PrintAttributes printAttributes) {
    int itemsPerPage = 4; // default item count for portrait mode

    MediaSize pageSize = printAttributes.getMediaSize();
    if (!pageSize.isPortrait()) {
        // Six items per page in landscape orientation
        itemsPerPage = 6;
    }

    // Determine number of print items
    int printItemCount = 5; //getPrintItemCount();

    return (int) Math.ceil(printItemCount / itemsPerPage);
}

private void drawPage(PdfDocument.Page page) {
    Canvas canvas = page.getCanvas();

    // units are in points (1/72 of an inch)
    int titleBaseLine = 72;
    int leftMargin = 54;

    Paint paint = new Paint();
    paint.setColor(Color.BLACK);
    paint.setTextSize(36);
    canvas.drawText("Test Title", leftMargin, titleBaseLine, paint);

    paint.setTextSize(11);
    canvas.drawText("Test paragraph", leftMargin, titleBaseLine + 25, paint);

    paint.setColor(Color.BLUE);
    canvas.drawRect(100, 100, 172, 172, paint);
   }

  }

请帮助我

最佳答案

对于 Hp 打印机,您可以通过查找您的电子邮件地址来使用 Hp-eprint HP 打印机,然后您可以使用以下代码将邮件发送到您的打印机。 您发送的邮件所附文档将在您的 HP 打印机上打印。

 private void openHpeprint() {
        File file = new File(folder + "/" + fileName);
        if (file.exists()) {
                Intent emailIntent = new Intent();
                emailIntent.setAction(Intent.ACTION_SEND);
             /*   Uri uri = Uri.fromFile(file);*/
                Uri uri = FileProvider.getUriForFile(mContext, mContext.getApplicationContext().getPackageName() + ".provider", file);
                emailIntent.setFlags(FLAG_GRANT_WRITE_URI_PERMISSION);
                emailIntent.setFlags(FLAG_GRANT_READ_URI_PERMISSION);
                // set the type to 'email'
                emailIntent.setType("vnd.android.cursor.dir/email");
                emailIntent.setPackage("com.google.android.gm");
                String to[] = {"yourHpprinteremailaddress@Hpeprint.com"};
                emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
// the attachment
                emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
// the mail subject
                emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
                try {
                    startActivity(emailIntent);
                } catch (ActivityNotFoundException e) {
                    Logger.LogError(TAG, "No Application Available to View Pdf");
                }

        }
    }

关于java - E/PdfManipulationService : Cannot open file java. io.IOException : not create document. 错误:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43998772/

相关文章:

java - Mockito.verify 方法包含 boolean 值和参数捕获器

java - JTextPane,文本/html 内容 : nested HTML element do not inherit font size?

java - 哈多普 : datanode not running?

android - 手机已 root 但无法从/data/data 文件夹中提取文件

android - 批量发布安卓应用

php - 如何将外部文件的内容发送到打印机?

python-3.x - Python win32 ShellExecute 错误 31 : 'A device attached to the system is not functioning.'

java - 非Spring Boot项目如何使用@Scheduled注解

android - 简单 HttpPost 上的 NullPointerException

c - 尝试打印结构元素,但结果为空白。 - C