Skip to content

Instantly share code, notes, and snippets.

@daichan4649
Created November 12, 2012 09:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daichan4649/4058331 to your computer and use it in GitHub Desktop.
Save daichan4649/4058331 to your computer and use it in GitHub Desktop.
show PDF (for Android)
public class PdfUtil {
public enum PdfType {
SAMPLE("sample.pdf");
private static final String TMP_DIR_ROOT = "/mnt/sdcard/";
private String fileName;
private PdfType(String fileName) {
this.fileName = fileName;
}
public String getFileName() {
return fileName;
}
public String getFilePath() {
return TMP_DIR_ROOT + fileName;
}
}
public static void showPdf(Context context, PdfType type) {
File pdf = createPdf(context, type);
Uri uri = Uri.parse("file://" + pdf.getAbsolutePath());
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/pdf");
context.startActivity(intent);
}
private static File createPdf(Context context, PdfType type) {
File pdf = null;
AssetManager manager = context.getAssets();
OutputStream os = null;
InputStream is = null;
try {
is = manager.open(type.getFileName());
pdf = new File(type.getFilePath());
os = new FileOutputStream(pdf);
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) > 0) {
os.write(buf, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
return pdf;
}
}
@daichan4649
Copy link
Author

assets 内に保存した pdf ファイルを読み込むサンプル。
直接開けないので、いったんSDカード(or 本体)に保存する必要あり。

SDカード内に保存するのであれば、 AndroidManifest.xml に以下を追記。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment