Android 以编程方式打开pdf文件
我正在写pdf。我正在尝试使用下面的代码从我的应用程序中打开一个pdf文件。但我没能打开Android 以编程方式打开pdf文件,android,Android,我正在写pdf。我正在尝试使用下面的代码从我的应用程序中打开一个pdf文件。但我没能打开 private void openPdf() { File file = new File("mnt/sdcard.test.pdf"); Uri path = Uri.fromFile(file); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setFlags(Intent.
private void openPdf() {
File file = new File("mnt/sdcard.test.pdf");
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(path);
intent.setType("application/pdf");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), "No application found",
Toast.LENGTH_SHORT).show();
}
}
当我在emulator中尝试这段代码时,它显示了一个祝酒词“找不到应用程序”(bcoz,emulator中通常没有安装pdf查看应用程序)。当我在设备中测试同样的东西时(特别是在funbook标签和sony标签中),它既没有显示Toast消息,也没有打开pdf文件。有人能指出我代码中的错误吗。实际上,我是第一次使用pdf。所以我的问题是,
我认为您只是缺少adobe包intent.setPackage(“com.adobe.reader”) 虽然我没有在我的应用程序中打开SD卡中的文件,但我有几乎相同的代码可以正常工作
Activity mActivity = /* your activity */...;
String mFileName = /* path of my PDF file */...;
Uri uri = Uri.fromFile(mActivity.getFileStreamPath(mFileName));
try
{
Intent intentUrl = new Intent(Intent.ACTION_VIEW);
intentUrl.setDataAndType(uri, "application/pdf");
intentUrl.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mActivity.startActivity(intentUrl);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(mActivity, "No PDF Viewer Installed", Toast.LENGTH_LONG).show();
}
所以你的方法是正确的。确保您可以先打开该文件。。。i、 e.使用mActivity.openFileInput()确保您有一个可读的PDF。我找到了上述问题的解决方案,所以请再试一次 步骤:-
按钮
,图像视图
,图像按钮
)openPDFFiles()
private void openPDFFiles() {
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), “schedule1.pdf”);//here schedule1.pdf is the pdf file name which is keep in assets folder.
try {
in = assetManager.open(“schedule1.pdf”);
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e(“tag”, e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(“file://” + getFilesDir() + “/schedule1.pdf”), “application/pdf”);
startActivity(intent);
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
您可以使用第三方库集成来实现这一点。下面列出了工作库, 使用SDK
与NDK 使用指南 @
在此处下载源代码() 在Gradle文件中添加此依赖项:
compile 'com.github.barteksc:android-pdf-viewer:2.0.3'
活动\u main.xml
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
xmlns:android="http://schemas.android.com/apk/res/android" >
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="@color/colorPrimaryDark"
android:text="View PDF"
android:textColor="#ffffff"
android:id="@+id/tv_header"
android:textSize="18dp"
android:gravity="center"></TextView>
<com.github.barteksc.pdfviewer.PDFView
android:id="@+id/pdfView"
android:layout_below="@+id/tv_header"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
MainActivity.java
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.provider.OpenableColumns;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;
import java.util.List;
public class MainActivity extends Activity implements OnPageChangeListener,OnLoadCompleteListener{
private static final String TAG = MainActivity.class.getSimpleName();
public static final String SAMPLE_FILE = "android_tutorial.pdf";
PDFView pdfView;
Integer pageNumber = 0;
String pdfFileName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pdfView= (PDFView)findViewById(R.id.pdfView);
displayFromAsset(SAMPLE_FILE);
}
private void displayFromAsset(String assetFileName) {
pdfFileName = assetFileName;
pdfView.fromAsset(SAMPLE_FILE)
.defaultPage(pageNumber)
.enableSwipe(true)
.swipeHorizontal(false)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(new DefaultScrollHandle(this))
.load();
}
@Override
public void onPageChanged(int page, int pageCount) {
pageNumber = page;
setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
}
@Override
public void loadComplete(int nbPages) {
PdfDocument.Meta meta = pdfView.getDocumentMeta();
printBookmarksTree(pdfView.getTableOfContents(), "-");
}
public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
for (PdfDocument.Bookmark b : tree) {
Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));
if (b.hasChildren()) {
printBookmarksTree(b.getChildren(), sep + "-");
}
}
}
}
导入android.app.Activity;
导入android.database.Cursor;
导入android.net.Uri;
导入android.provider.OpenableColumns;
导入android.support.v7.app.AppActivity;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.view;
导入android.widget.ImageView;
导入android.widget.RelativeLayout;
导入com.github.barteksc.pdfviewer.PDFView;
导入com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
导入com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
导入com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
导入com.shockwave.pdfium.PdfDocument;
导入java.util.List;
公共类MainActivity扩展活动实现OnPageChangeListener、OnLoadCompleteListener{
私有静态最终字符串标记=MainActivity.class.getSimpleName();
公共静态最终字符串SAMPLE\u FILE=“android\u tutorial.pdf”;
PDFView PDFView;
整数页码=0;
字符串pdfFileName;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pdfView=(pdfView)findViewById(R.id.pdfView);
displayFromAsset(示例文件);
}
私有void displayFromAsset(字符串assetFileName){
pdfFileName=assetFileName;
pdfView.fromAsset(示例文件)
.defaultPage(页码)
.enableSwipe(真)
.swipeHorizontal(错误)
.onPageChange(此)
.enableAnnotationRendering(真)
.onLoad(此)
.scrollHandle(新的DefaultScrollHandle(此))
.load();
}
@凌驾
公共无效页已更改(整页,整页计数){
页码=页码;
setTitle(String.format(“%s%s/%s”,pdfFileName,第+1页,pageCount));
}
@凌驾
公共无效加载完成(整版){
PdfDocument.Meta=pdfView.getDocumentMeta();
printBookmarksTree(pdfView.getTableOfContents(),“-”;
}
public void printBookmarksTree(列表树,字符串sep){
for(PdfDocument.Bookmark b:树){
Log.e(TAG,String.format(“%s%s,p%d”,sep,b.getTitle(),b.getPageIdx());
if(b.haschilds()){
printBookmarksTree(b.getChildren(),sep+“-”;
}
}
}
}
我知道答案可能太迟了,但您的问题是由以下两行引起的:
intent.setData(路径)代码>
intent.setType(“application/pdf”)代码>
当您设置数据并在设置类型之后,第二个命令将清除setData中分配的路径。
在这种情况下,您应该使用setDataAndType(路径,“application/pdf”)
/**
*设置显式MIME数据类型。
*
*这用于创建只指定类型而不指定数据的意图,
*例如,指示要返回的数据类型。
*
*此方法会自动清除所有已删除的数据
*以前设置(例如通过{@link#setData})。
*
*注意:Android框架中的MIME类型匹配是
*区分大小写,与正式的RFC MIME类型不同。因此,
*您应该始终使用小写字母编写MIME类型,
*或者使用{@link#normalizeMimeType}或{@link#setTypeAndNormalize}
*以确保将其转换为小写。
*
*@param type此意图处理的数据的MIME类型。
*
*@return返回相同的Intent对象,用于链接多个调用
*变成一句话。
*
*@see#getType
*@请参见#设置类型和规格化
*@see#setDataAndType
*@see#normalizeemimetype
*/
公共意图集合类型(字符串类型){
mData=null;
mType=类型;
归还这个;
}
对于/**
* Set an explicit MIME data type.
*
* <p>This is used to create intents that only specify a type and not data,
* for example to indicate the type of data to return.
*
* <p>This method automatically clears any data that was
* previously set (for example by {@link #setData}).
*
* <p><em>Note: MIME type matching in the Android framework is
* case-sensitive, unlike formal RFC MIME types. As a result,
* you should always write your MIME types with lower case letters,
* or use {@link #normalizeMimeType} or {@link #setTypeAndNormalize}
* to ensure that it is converted to lower case.</em>
*
* @param type The MIME type of the data being handled by this intent.
*
* @return Returns the same Intent object, for chaining multiple calls
* into a single statement.
*
* @see #getType
* @see #setTypeAndNormalize
* @see #setDataAndType
* @see #normalizeMimeType
*/
public Intent setType(String type) {
mData = null;
mType = type;
return this;
}
public class GenericFileProvider extends FileProvider {
}
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
</paths>
<provider
android:name=".Model.Utilitys.GenericFileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
String fileName="yourfile.pdf";
File file = new File(Environment.getExternalStorageDirectory()+"/Android/data/ir.tdaapp.paymanyar/files/File",fileName);
String extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_NEW_TASK);
Uri uri = FileProvider.getUriForFile(getContext(), getActivity().getApplicationContext().getPackageName() + ".provider", file);
intent.setDataAndType(uri, mimeType);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(intent, "choseFile"));
android:requestLegacyExternalStorage="true"