你好,我正在处理文档打印应用程序,首先我使用 iText lib 创建一个pdf文件然后我连接打印机通过IP地址这是顺利,但当我打印(惠普打印机)文件,然后我有一个错误
如下面的错误
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)
我的代码是
MainActivity
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);
}
}
请帮帮我
答案 0 :(得分:0)
对于Hp打印机,您可以通过查找您的电子邮件地址来使用Hp-eprint 惠普打印机,然后您可以使用以下代码将邮件发送给您的priner.As 您发送邮件将附加的文件打印在您的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");
}
}
}