下载后打开pdf

时间:2016-09-28 21:39:11

标签: android pdf

我使用此代码下载pdf

#import "ViewController.h"

@interface ViewController () <UITextViewDelegate>

@property (weak, nonatomic) IBOutlet UITextView *lyricsTxtView;

@end

@implementation ViewController

 //check for text view input
-(BOOL)textView:(UITextView*)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{


     //create string textViewText with text view text
    NSString *textViewText = [_lyricsTxtView text];
    NSLog(@"UITextView text: %@", textViewText);

     //create mutable attributed string with string textViewText
    NSMutableAttributedString *textViewTextMut =[[NSMutableAttributedString alloc] initWithString: textViewText];
    NSLog(@"UITextView attributable text: %@", textViewTextMut);

    //create array of words by separating string textViewText by spaces
    NSArray *words = [textViewText componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSLog(@"word array: %@", words);

    /*NOW WE HAVE ESTABLISHED THE UITEXTVIEW TEXT IN ATTRIBUTABLE FORM AND AN ARRAY OF WORDS TO START ANAYLYZING LETTERS*/

    //declare mutable array for first letters
    NSMutableArray *letters1;

    //add first letters of each word in array words to array letters1
    for (NSString *word in words) {
       if ([word length] > 0){
          NSString *firstLetter = [word substringToIndex:1];
          [letters1 addObject: firstLetter];
    }
       else {
          continue;
       }

    }
    NSLog(@"first array of first letters: %@", letters1);

    //create array letters2 matching letters1
    NSArray *letters2 = letters1;
    NSLog(@"second array of first letters: %@", letters2);

    /*NOW WE ALSO HAVE TWO ARRAYS OF EVERY WORDS' FIRST LETTER, SO WE CAN START COMPARING LETTERS*/

    //compare all letters in letters1 with all letters in letters2
    for (NSString *letter1 in letters1) {
        for (NSString *letter2 in letters2) {

    //check for matching letters
            if ([letter1 isEqualToString:letter2]) {

    //check if letters have the same index, and...
                NSUInteger letter1Index = [letters1 indexOfObject:letter1];
                NSUInteger letter2Index = [letters2 indexOfObject:letter2];

    //if they don't, get the index of string word in array words who's index matches the index of string letter1 in array letters1 and the string word in array words who's index matches the index of string letter2 in array letters2. store them in an array. but...
                NSMutableArray *matchWords;
                if (letter1Index != letter2Index) {
                    for (NSString *word in words) {
                        if ([word isEqual:words[letter1Index]] ||
                            [word isEqual:words[letter2Index]]) {

                            [matchWords addObject: word];
                            NSLog(@"array of matching words: %@", matchWords);

    //attribute word within nested loops, which will account for all words with the matching letter.
                            NSRange range=[textViewText rangeOfString:word];

                            [textViewTextMut addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
                        }

                    }

                }

    //if they do, do nothing because we are comparing a word's first letter with itself.
                else {
                    continue;
                }

            }
        }

    /*WE HAVE CHOSEN TO DO NOTHING WHEN MATCHING LETTERS TURN OUT TO BE ANALYZED ON THE SAME WORD. WHEN THEY ARE FOUND TO BE MATCHING LETTERS IN SEPARATE WORDS, THE WORDS ARE ATTRIBUTED.*/
    }

    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [_lyricsTxtView setDelegate:self];
}

它运行良好,pdf在android / data

中的app文件夹中下载

我使用此代码打开pdf

downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                                        Uri uri = Uri.parse(url);
                                        DownloadManager.Request request = new DownloadManager.Request(uri);
                                        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                                        request.setTitle("story" + name);
                                        request.setDescription("download " + name);
                                        request.setDestinationInExternalFilesDir(R_arabic.this,"/Rewayat/", name+".pdf");
                                        Long reference = downloadManager.enqueue(request);

但是当我尝试打开它时,我没有得到正确的pdf文件并获取错误文件 我觉得路径不对,请帮帮我

1 个答案:

答案 0 :(得分:0)

将文档下载到外部存储

DownloadManager.Request r = new DownloadManager.Request(Uri.parse(document_url));

// This puts the downloaded document in the Download directory
r.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "my_document.pdf");  
r.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);        
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(r);

要打开的代码

public void OpenPDF() {
    try {
        File file = new File(Environment.getExternalStorageDirectory()
                + "/Download/" + "my_document.pdf");
        if (!file.isDirectory())
            file.mkdir();
        Intent pdfIntent = new Intent("com.adobe.reader");
        pdfIntent.setType("application/pdf");
        pdfIntent.setAction(Intent.ACTION_VIEW);
        Uri uri = Uri.fromFile(file);
        pdfIntent.setDataAndType(uri, "application/pdf");
        startActivity(pdfIntent);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

您需要获得编写外部存储空间的权限,检查如何获取新Android版本的权限(您必须通过代码请求权限,而不仅仅是在清单中)

要请求用户授权以编写外部存储空间,请将这两种方法放在主要活动

public  boolean isStoragePermissionGranted() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    == PackageManager.PERMISSION_GRANTED) {
                Log.v("PERMISSIONS", "Permission is granted");
                return true;
            } else {

                Log.v("PERMISSIONS","Permission is revoked");
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                return false;
            }
        }
        else { //permission is automatically granted on sdk<23 upon installation
            Log.v("PERMISSIONS","Permission is granted");
            return true;
        }


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
            Log.v("PERMISSIONS","Permission: "+permissions[0]+ "was "+grantResults[0]);
            //resume tasks needing this permission
        }
    }

并在onCreate中,调用方法

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // ...
        isStoragePermissionGranted();

<application>标记之前的manifest.xml中放入了这两个权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>