Created
November 12, 2012 09:22
-
-
Save daichan4649/4058331 to your computer and use it in GitHub Desktop.
show PDF (for Android)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
assets 内に保存した pdf ファイルを読み込むサンプル。
直接開けないので、いったんSDカード(or 本体)に保存する必要あり。
SDカード内に保存するのであれば、 AndroidManifest.xml に以下を追記。