我需要在我的应用中显示在线pdf文件。我正在使用第三方API,但问题是它没有显示在线文件 这是我的代码
compile 'com.github.barteksc:android-pdf-viewer:2.5.1'
compile 'org.apache.commons:commons-io:1.3.2'
我的xml文件
<com.github.barteksc.pdfviewer.PDFView
android:id="@+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
这是我在PDFview中呈现在线pdf文件的最终代码
Uri uri = Uri.parse("http://www.pdf995.com/samples/pdf.pdf");
mypdfview =(PDFView)findViewById(R.id.pdfView);
mypdfview.fromUri(uri)
.pages(0, 2, 1, 3, 3, 3) // all pages are displayed by default
.enableSwipe(true) // allows to block changing pages using swipe
.swipeHorizontal(false)
.enableDoubletap(true)
.defaultPage(0)
.onDraw(this) // allows to draw something on a provided canvas, above the current page
.onLoad(this) // called after document is loaded and starts to be rendered
.onPageChange(this)
.onPageScroll(this)
.onError(this)
.onRender(this) // called after document is rendered for the first time
.enableAnnotationRendering(false) // render annotations (such as comments, colors or forms)
.password(null)
.scrollHandle(null)
.enableAntialiasing(true) // improve rendering a little bit on low-res screens
.load();
我面临的问题是我可以从资产文件夹中显示文件。但是当我通过uri然后它没有显示任何东西。 我还在清单中给予了互联网许可和外部数据读取许可。
答案 0 :(得分:1)
答案 1 :(得分:0)
或者,您可以使用Webview加载pdf
webView.loadUrl(&#34; http://docs.google.com/gview?embedded=true&url=&#34; + pdfUrl);
WebView webView = (WebView) findViewById(R.id.my_webview);
webView.setWebViewClient(new MyWebViewClient());
webView.addView(webView.getZoomControls());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://docs.google.com/gview?embedded=true&url=" +pdfUrl);
答案 2 :(得分:0)
您可以使用webview在应用程序中查看pdf,而不是使用其他控件
String url = "http://docs.google.com/gview?embedded=true&url=" + yourURL;
String doc="<iframe src='"+url+"' width='100%' height='100%' style='border: none;'></iframe>";
WebView web=(WebView)findViewById(R.id.webViewpdf);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadData(doc, "text/html", "UTF-8");
答案 3 :(得分:0)
这可以帮助您How to open/display documents(.pdf, .doc) without external app?
在成绩中添加此依赖项:
compile 'com.github.barteksc:android-pdf-viewer:2.0.3'
<强> activity_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 强>
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 + "-");
}
}
}
}
答案 4 :(得分:0)
首先,您应该使用Asynctask读取pdf文件,然后加载...
这是对我有用的代码...
请注意,我正在使用pdfview库显示pdf
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
!!! online_pdf是包含pdf网址的字符串变量
首先使LOADURL类扩展AsyncTask
public class LOADURL extends AsyncTask<String,Void,InputStream>
{
private ProgressDialog progressDialog;
public LOADURL(LoadPDF loadPdf) {
progressDialog = new ProgressDialog(loadPdf);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setTitle("Please wait");
progressDialog.setMessage("Fetching PDF from server...");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
@Override
protected InputStream doInBackground(String... strings) {
InputStream inputStream = null;
try
{
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
if (urlConnection.getResponseCode()==200)
{
inputStream = new
BufferedInputStream(urlConnection.getInputStream());
}
} catch (IOException e) {
return null;
}
return inputStream;
}
@Override
protected void onPostExecute(InputStream inputStream) {
pdfFileName = getFileName(mypdf);
pdfViewer.fromStream(inputStream)
.defaultPage(pageNumber)
.onPageChange(LoadPDF.this)
.enableAnnotationRendering(true)
.onLoad(LoadPDF.this)
.scrollHandle(new DefaultScrollHandle(LoadPDF.this))
.spacing(10) // in dp
.onPageError(LoadPDF.this)
.onError(LoadPDF.this)
.onPageError(LoadPDF.this)
.enableAnnotationRendering(false)
.enableAntialiasing(true)
.onRender(LoadPDF.this)
.load();
progressDialog.dismiss();
}
}
在那之后,调用onCreate视图中的类...
LOADURL loadurl = new LOADURL(LoadPDF.this);
loadurl.execute(online_pdf);
答案 5 :(得分:0)
您可以使用Android SDK提供的PDFRenderer(在API级别21中添加)在Android应用程序中呈现PDF。下载PDF并将其保存在本地存储中,并使用以下代码在应用程序内部呈现它。
PdfRendererAdapter.kt
class PdfRendererAdapter(
private val renderer: PdfRenderer?,
private val pageWidth: Int
) : RecyclerView.Adapter<PdfRendererAdapter.ViewHolder>() {
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
private val imageView: ImageView = view.imageView
fun bind(bitmap: Bitmap) = imageView.setImageBitmap(bitmap)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
ViewHolder(
LayoutInflater.from(parent.context).inflate(R.layout.pdf_page_item, parent, false)
)
override fun getItemCount() = renderer!!.pageCount
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val currentPage = renderer?.openPage(position)
val bitmap = currentPage!!.render(pageWidth)
holder.bind(bitmap)
}
}
PDFRendererExtensions.kt
fun PdfRenderer.Page.render(width: Int): Bitmap {
val bitmap = createBitmap(width)
render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY)
close()
return bitmap
}
private fun PdfRenderer.Page.createBitmap(bitmapWidth: Int): Bitmap {
val bitmap = Bitmap.createBitmap(
bitmapWidth, (bitmapWidth.toFloat() / width * height).toInt(), Bitmap.Config.ARGB_8888
)
val canvas = Canvas(bitmap)
canvas.drawColor(Color.WHITE)
canvas.drawBitmap(bitmap, 0f, 0f, null)
return bitmap
}
PDFRendererActivity.kt
class PdfRenderActivity : AppCompatActivity() {
private var pdfRenderer: PdfRenderer? = null
private var currentPage: PdfRenderer.Page? = null
private var parcelFileDescriptor: ParcelFileDescriptor? = null
companion object {
const val FILE_NAME = "testPDF.pdf"
private const val INTENT_PDF_FILE = "pdf_file"
fun getCallingIntent(context: Context, pdfFile: File): Intent {
val intent = Intent(context, PdfRenderActivity::class.java)
intent.putExtra(INTENT_PDF_FILE, pdfFile)
return intent
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_pdf_renderer)
openRenderer()
showPagesInRecyclerView()
}
private fun showPagesInRecyclerView() {
currentPage = pdfRenderer!!.openPage(0)
val pdfAdapter = PdfRendererAdapter(renderer = pdfRenderer, pageWidth = currentPage!!.width)
currentPage!!.close()
pdf_rv.adapter = pdfAdapter
pdf_rv.layoutManager =
LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
}
public override fun onStop() {
try {
closeRenderer()
} catch (e: IOException) {
e.printStackTrace()
}
super.onStop()
}
private fun openRenderer() {
val file = intent.extras?.get(INTENT_PDF_FILE) as File
parcelFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
if (parcelFileDescriptor != null) {
pdfRenderer = PdfRenderer(parcelFileDescriptor!!)
}
}
private fun closeRenderer() {
pdfRenderer!!.close()
parcelFileDescriptor!!.close()
}
}
答案 6 :(得分:0)
这是在应用程序中加载远程 pdf 的最佳方式
WebView wv = (WebView)findViewById(R.id.webview);
wv.getSettings().setJavaScriptEnabled(true);
wv.setWebViewClient(new WebViewClient());
wv.getSettings().setAllowFileAccess(true);
String src="http://docs.google.com/gview?embedded=true&url=https://firebasestorage.googleapis.com/v0/b/tuloenaseerapp.appspot.com/o/2_arsh_e_naaz_hq_compressed.pdf?alt=media&token=607c124b-ac28-4560-9854-1fe7d023f813";
wv.loadUrl(src);