Java Examples for android.graphics.pdf.PdfRenderer

The following java examples will help you to understand the usage of android.graphics.pdf.PdfRenderer. These source code samples are taken from different open source projects.

Example 1
Project: pdf-renderer-master  File: PdfRendererBasicFragment.java View source code
/**
     * Sets up a {@link android.graphics.pdf.PdfRenderer} and related resources.
     */
private void openRenderer(Context context) throws IOException {
    // In this sample, we read a PDF from the assets directory.
    File file = new File(context.getCacheDir(), FILENAME);
    if (!file.exists()) {
        // Since PdfRenderer cannot handle the compressed asset file directly, we copy it into
        // the cache directory.
        InputStream asset = context.getAssets().open(FILENAME);
        FileOutputStream output = new FileOutputStream(file);
        final byte[] buffer = new byte[1024];
        int size;
        while ((size = asset.read(buffer)) != -1) {
            output.write(buffer, 0, size);
        }
        asset.close();
        output.close();
    }
    mFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
    // This is the PdfRenderer we use to render the PDF.
    mPdfRenderer = new PdfRenderer(mFileDescriptor);
}
Example 2
Project: cw-omnibus-master  File: PageController.java View source code
void setPage(PdfRenderer.Page page) {
    if (bitmap == null) {
        int height = 2000;
        int width = height * page.getWidth() / page.getHeight();
        bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    }
    bitmap.eraseColor(0xFFFFFFFF);
    page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
    iv.resetScaleAndCenter();
    iv.setImage(ImageSource.cachedBitmap(bitmap));
}
Example 3
Project: SmartReceiptsLibrary-master  File: LollipopPdfPDImageXFactory.java View source code
@NonNull
@Override
public PDImageXObject get() throws IOException {
    Preconditions.checkNotNull(pdfRenderer, "The Pdf file must first be opened");
    Preconditions.checkNotNull(parcelFileDescriptor, "The Pdf file must first be opened");
    PdfRenderer.Page page = null;
    Bitmap bitmap = null;
    try {
        Logger.debug(this, "Beginning the render of PDF page {} at {}", currentPage, System.currentTimeMillis());
        page = pdfRenderer.openPage(currentPage);
        final int scaledHeight = (int) IMAGE_QUALITY_SCALING_FACTOR * page.getHeight();
        final int scaledWidth = (int) IMAGE_QUALITY_SCALING_FACTOR * page.getWidth();
        final Rect destClip = new Rect(0, 0, scaledWidth, scaledHeight);
        bitmap = Bitmap.createBitmap(scaledWidth, scaledHeight, Bitmap.Config.ARGB_8888);
        page.render(bitmap, destClip, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
        try {
            bitmap = ImageUtils.applyWhiteBackground(bitmap);
            bitmap = ImageUtils.changeCodec(bitmap, Bitmap.CompressFormat.JPEG, 100);
            Logger.debug(this, "Creating pdf image from converted JPEG to speed up processing time");
            return JPEGFactory.createFromImage(pdDocument, bitmap);
        } catch (IOException e) {
            Logger.warn(this, "Failed to convert to JPG to speed up our processing. Creating the bitmap from our lossless factory of PDF page {} at {}", currentPage, System.currentTimeMillis());
            return LosslessFactory.createFromImage(pdDocument, bitmap);
        }
    } finally {
        Logger.debug(this, "Completing the render of PDF page {} at {}", currentPage, System.currentTimeMillis());
        if (page != null) {
            page.close();
        }
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
        }
    }
}
Example 4
Project: BookReader-master  File: PDFPagerAdapter.java View source code
@Override
@SuppressWarnings("NewApi")
public Object instantiateItem(ViewGroup container, int position) {
    View v = inflater.inflate(R.layout.view_pdf_page, container, false);
    ImageView iv = (ImageView) v.findViewById(R.id.imageView);
    if (renderer == null || getCount() < position) {
        return v;
    }
    PdfRenderer.Page page = getPDFPage(renderer, position);
    Bitmap bitmap = bitmapContainer.get(position);
    page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
    page.close();
    PhotoViewAttacher attacher = new PhotoViewAttacher(iv);
    attacher.setScale(scale.getScale(), scale.getCenterX(), scale.getCenterY(), true);
    attacher.setOnMatrixChangeListener(this);
    attachers.put(position, new WeakReference<PhotoViewAttacher>(attacher));
    iv.setImageBitmap(bitmap);
    attacher.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {

        @Override
        public void onPhotoTap(View view, float x, float y) {
            if (pageClickListener != null) {
                pageClickListener.onPageTap(view, x, y);
            }
        }
    });
    attacher.update();
    container.addView(v, 0);
    return v;
}
Example 5
Project: platform_frameworks_base-master  File: PdfManipulationService.java View source code
@Override
public int openDocument(ParcelFileDescriptor source) throws RemoteException {
    synchronized (mLock) {
        try {
            throwIfOpened();
            if (DEBUG) {
                Log.i(LOG_TAG, "openDocument()");
            }
            mRenderer = new PdfRenderer(source);
            return mRenderer.getPageCount();
        } catch (IOExceptionIllegalStateException |  e) {
            IoUtils.closeQuietly(source);
            Log.e(LOG_TAG, "Cannot open file", e);
            return ERROR_MALFORMED_PDF_FILE;
        } catch (SecurityException e) {
            IoUtils.closeQuietly(source);
            Log.e(LOG_TAG, "Cannot open file", e);
            return ERROR_SECURE_PDF_FILE;
        }
    }
}
Example 6
Project: OpenSongTablet-master  File: FullscreenActivity.java View source code
// This bit draws the lyrics stored in the variable to the page.
private void showLyrics(View view) throws IOException, IllegalStateException {
    chordimageshere.removeAllViews();
    allchords = "";
    allchordscapo = "";
    mScaleFactor = 1.0f;
    if (toggleYScale.equals("N")) {
        needtoredraw = false;
        columnTest = 1;
        tempfontsize = mFontSize;
    }
    // Get the autoscroll info initialised
    if (mtask_autoscroll_music != null) {
        mtask_autoscroll_music.cancel(true);
    }
    // Turn off the autoscroll if it was on
    autoscrollispaused = false;
    scrollpage.smoothScrollTo(0, 0);
    popupAutoscroll_stoporstart = "stop";
    popupAutoscroll_startstopbutton.setText(getResources().getString(R.string.start));
    autoscrollonoff = "off";
    isautoscrolling = false;
    if (popupAutoscroll.getVisibility() != View.VISIBLE) {
        autoscrollButton.setAlpha(0.4f);
    }
    if (!alreadyloaded && !isPDF) {
        // Load up the song
        pdfPageCurrent = 0;
        pdfPageCount = 0;
        try {
            LoadXML.loadXML();
            alreadyloaded = true;
        } catch (XmlPullParserException e1) {
            e1.printStackTrace();
        }
        if (needtorefreshsongmenu) {
            prepareSongMenu();
            needtorefreshsongmenu = false;
        }
        // Decide if there is a valid link audio file and if so, show the link icon to get the duration from it
        getAudioLength();
        if (audiolength > -1) {
            uselinkaudiolength_ImageButton.setVisibility(View.VISIBLE);
        } else {
            uselinkaudiolength_ImageButton.setVisibility(View.GONE);
        }
        // Find out if the song is in the current set
        // Only if there is only one occurence of the song in the set
        int count = 0;
        for (String aMSet : mSet) {
            if (aMSet.equals(whatsongforsetwork)) {
                count++;
            }
        }
        if (count < 2) {
            if (SetActions.isSongInSet()) {
                invalidateOptionsMenu();
            }
        }
        // If there isn't a key specified, or the user wants the pad off, or an invalid linkAudio,
        // make sure the padButton is turned off
        // User will be prompted to specify a key if they press the button again
        boolean stoppad = false;
        boolean badlinkaudio = false;
        // Test the audio file is there by assigning it to a temp mediaplayer
        MediaPlayer testMPlayer = new MediaPlayer();
        try {
            testMPlayer.setDataSource(this, Uri.parse(mLinkAudio));
            testMPlayer.prepare();
            testMPlayer.reset();
        } catch (Exception e) {
            testMPlayer.reset();
            badlinkaudio = true;
        }
        testMPlayer.release();
        if (!mPadFile.equals(getResources().getString(R.string.off)) && !mPadFile.equals(getResources().getString(R.string.link_audio)) && (mKey.isEmpty() || mKey.equals("")) && padson) {
            // Trying to play a pad and the key isn't set
            myToastMessage = getResources().getString(R.string.pad_error);
            stoppad = true;
        } else if (mPadFile.equals(getResources().getString(R.string.off)) && padson) {
            // Pad has been turned off for this song
            myToastMessage = getResources().getString(R.string.pad) + " - " + getResources().getString(R.string.off);
            stoppad = true;
        } else if (mPadFile.equals(getResources().getString(R.string.link_audio)) && (mLinkAudio.isEmpty() || badlinkaudio) && padson) {
            // Want a link audio, but the audio link is either empty or invalid audio
            myToastMessage = getResources().getString(R.string.link_audio) + " - " + getResources().getString(R.string.file_type_unknown);
            stoppad = true;
        }
        if (stoppad) {
            if (!myToastMessage.isEmpty()) {
                ShowToast.showToast(FullscreenActivity.this);
            }
            padson = false;
            if (mPlayer1 != null) {
                if (mPlayer1.isPlaying()) {
                    //whichtofadeout = 1;
                    fadeout1 = true;
                    popupPad_startstopbutton.setText(getResources().getString(R.string.wait));
                    popupPad_startstopbutton.setBackgroundDrawable(getResources().getDrawable(R.drawable.grey_button));
                    popupPad_startstopbutton.setEnabled(false);
                    isfading1 = false;
                    fadeOutBackgroundMusic1();
                }
            }
            if (mPlayer2 != null) {
                if (mPlayer2.isPlaying()) {
                    //whichtofadeout = 2;
                    fadeout2 = true;
                    popupPad_startstopbutton.setText(getResources().getString(R.string.wait));
                    popupPad_startstopbutton.setBackgroundDrawable(getResources().getDrawable(R.drawable.grey_button));
                    popupPad_startstopbutton.setEnabled(false);
                    isfading2 = false;
                    fadeOutBackgroundMusic2();
                }
            }
            if (popupPad.getVisibility() != View.VISIBLE) {
                padButton.setAlpha(0.4f);
            }
        }
        if ((mPlayer1 == null && mPlayer2 == null) || (mPlayer1 != null && !mPlayer1.isPlaying()) && mPlayer2 != null && !mPlayer2.isPlaying()) {
            popupPad_stoporstart = "stop";
            padson = false;
            popupPad_startstopbutton.setEnabled(true);
            popupPad_startstopbutton.setText(getResources().getString(R.string.start));
            popupPad_startstopbutton.setBackgroundDrawable(getResources().getDrawable(R.drawable.blue_button));
            if (popupPad.getVisibility() != View.VISIBLE) {
                padButton.setAlpha(0.4f);
            }
            fadeout1 = false;
            fadeout2 = false;
        }
        // Set song key
        ProcessSong.processKey();
        popupPad_key.setSelection(keyindex);
        // Set the pad / backing track
        if (mPadFile.equals(getResources().getString(R.string.off))) {
            popupPad_file.setSelection(2);
        } else if (mPadFile.equals(getResources().getString(R.string.link_audio)) && !mLinkAudio.isEmpty() && !mLinkAudio.equals("")) {
            popupPad_file.setSelection(1);
        } else {
            popupPad_file.setSelection(0);
        }
        // Set the loop on or off
        if (mLoopAudio.equals("true")) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                popupPad_loopaudio.setChecked(true);
            }
        } else {
            mLoopAudio = "false";
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                popupPad_loopaudio.setChecked(false);
            }
        }
        // Set the pad volume and pan
        int temp_padvol = (int) (100 * padvol);
        popupPad_volume.setProgress(temp_padvol);
        String text = temp_padvol + " %";
        popupPad_volume_text.setText(text);
        switch(padpan) {
            case "left":
                popupPad_pan_text.setText("L");
                popupPad_pan.setProgress(0);
                break;
            case "right":
                popupPad_pan_text.setText("R");
                popupPad_pan.setProgress(2);
                break;
            default:
                popupPad_pan_text.setText("C");
                popupPad_pan.setProgress(1);
                break;
        }
        // Set the autoscroll values
        try {
            autoScrollDuration = Integer.parseInt(mDuration.replaceAll("[\\D]", ""));
        } catch (Exception e) {
            autoScrollDuration = -1;
        }
        try {
            autoScrollDelay = Integer.parseInt(mPreDelay.replaceAll("[\\D]", ""));
        } catch (Exception e) {
            autoScrollDelay = -1;
        }
        usingdefaults = false;
        if (mDuration.isEmpty() && autoscroll_default_or_prompt.equals("default")) {
            autoScrollDuration = default_autoscroll_songlength;
            usingdefaults = true;
        }
        if (mPreDelay.isEmpty() && autoscroll_default_or_prompt.equals("default")) {
            autoScrollDelay = default_autoscroll_predelay;
            usingdefaults = true;
        }
        if (autoScrollDelay < 0) {
            popupAutoscroll_delay.setProgress(0);
            text = "";
        } else {
            popupAutoscroll_delay.setProgress(autoScrollDelay + 1);
            text = autoScrollDelay + " s";
        }
        popupAutoscroll_delay_text.setText(text);
        String timetext = timeFormatFixer((autoScrollDuration));
        String start = "0:00";
        currentTime_TextView.setText(start);
        totalTime_TextView.setText(timetext);
        playbackProgress.setVisibility(View.INVISIBLE);
        if (autoScrollDuration < 0) {
            text = "";
        } else {
            text = autoScrollDuration + "";
        }
        popupAutoscroll_duration.setText(text);
        // Set time signature
        timesigindex = 0;
        ProcessSong.processTimeSig();
        popupMetronome_timesig.setSelection(timesigindex);
        // Process tempo
        ProcessSong.processTempo();
        if (temposlider < 1) {
            temposlider = 0;
            popupMetronome_tempo_text.setText(getResources().getString(R.string.notset));
        } else {
            popupMetronome_tempo_text.setText(mTempo);
        }
        popupMetronome_tempo.setProgress(temposlider);
        // Set the metronome volume and pan
        int temp_metronomevol = (int) (100 * metronomevol);
        popupMetronome_volume.setProgress(temp_metronomevol);
        text = temp_metronomevol + " %";
        popupMetronome_volume_text.setText(text);
        switch(metronomepan) {
            case "left":
                popupMetronome_pan_text.setText("L");
                popupMetronome_pan.setProgress(0);
                break;
            case "right":
                popupMetronome_pan_text.setText("R");
                popupMetronome_pan.setProgress(2);
                break;
            default:
                popupMetronome_pan_text.setText("C");
                popupMetronome_pan.setProgress(1);
                break;
        }
        // Alert the user for no timesig/tempo
        if (timesigindex == 0) {
            if (metroTask != null) {
                metroTask.cancel(true);
                metroTask.stop();
                if (metronomeonoff.equals("on")) {
                    promptTimeSig();
                }
            }
        } else if (temposlider == 0) {
            if (metroTask != null) {
                metroTask.cancel(true);
                metroTask.stop();
                if (metronomeonoff.equals("on")) {
                    promptTempo();
                }
            }
        }
        // Stop the original metronome and start a new one
        if (metroTask != null) {
            metroTask.cancel(true);
            metroTask.stop();
        }
        if (metronomeonoff.equals("on") && temposlider != 0 && timesigindex != 0) {
            ProcessSong.processTempo();
            bpm = (short) ((short) temposlider + 39);
            metroTask = new MetronomeAsyncTask();
            Runtime.getRuntime().gc();
            metronomeonoff = "on";
            popupMetronome_stoporstart = "start";
            popupMetronome_startstopbutton.setText(getResources().getString(R.string.stop));
            metroTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
        // Only play if this isn't called by an orientation change
        if (!orientationchanged && padson) {
            playPads(view);
        }
        // Now, reset the orientation.
        orientationchanged = false;
        // The whole group can still be hidden if the user specified it
        if (!isPDF && isSong && togglePageButtons.equals("Y")) {
            stickynotes.setVisibility(View.VISIBLE);
            autoscrollButton.setVisibility(View.VISIBLE);
            metronomeButton.setVisibility(View.VISIBLE);
            padButton.setVisibility(View.VISIBLE);
            linkButton.setVisibility(View.VISIBLE);
            chordButton.setVisibility(View.VISIBLE);
        } else {
            stickynotes.setVisibility(View.INVISIBLE);
            autoscrollButton.setVisibility(View.INVISIBLE);
            metronomeButton.setVisibility(View.INVISIBLE);
            padButton.setVisibility(View.INVISIBLE);
            linkButton.setVisibility(View.INVISIBLE);
            chordButton.setVisibility(View.INVISIBLE);
        }
        // Refresh the song list to the current song.
        if (mSongFileNames != null) {
            findSongInFolder();
        }
        // Strip out the lyrics, author, etc.
        LyricsDisplay.parseLyrics();
        // Split the song up into the bits we need
        LyricsDisplay.lookForSplitPoints();
        // Beautify the lyrics tags
        LyricsDisplay.replaceLyricsCode();
        // save preferences (current song being viewed)
        Preferences.savePreferences();
        invalidateOptionsMenu();
        // Make sure the tables are invisible while their content is prepared.
        lyricstable_onecolview.setVisibility(View.VISIBLE);
        lyricstable_twocolview.setVisibility(View.VISIBLE);
        lyricstable2_twocolview.setVisibility(View.VISIBLE);
        lyricstable_threecolview.setVisibility(View.VISIBLE);
        lyricstable2_threecolview.setVisibility(View.VISIBLE);
        lyricstable3_threecolview.setVisibility(View.VISIBLE);
        scrollpage_pdf.setVisibility(View.INVISIBLE);
        pdf_selectpage.setVisibility(View.INVISIBLE);
        scrollpage_onecol.setVisibility(View.INVISIBLE);
        scrollpage_twocol.setVisibility(View.INVISIBLE);
        scrollpage_threecol.setVisibility(View.INVISIBLE);
        if (toggleScrollArrows.equals("D")) {
            uparrow_bottom.setVisibility(View.INVISIBLE);
            downarrow_top.setVisibility(View.INVISIBLE);
        } else {
            uparrow_bottom.setVisibility(View.GONE);
            downarrow_top.setVisibility(View.GONE);
        }
        uparrow_top.setVisibility(View.INVISIBLE);
        downarrow_bottom.setVisibility(View.INVISIBLE);
    }
    // If the song is a PDF, turn stuff off that won't work
    if (isPDF) {
        hidepopupAutoscroll();
        hidepopupMetronome();
        hidepopupPad();
        hidepopupChord();
        hidepopupSticky();
        padButton.setAlpha(0.4f);
        metronomeButton.setAlpha(0.4f);
        autoscrollButton.setAlpha(0.4f);
        //Stop Autoscroll
        if (mtask_autoscroll_music != null) {
            mtask_autoscroll_music.cancel(true);
        }
        //Stop Metronome
        if (metroTask != null) {
            metroTask.cancel(true);
            metroTask.stop();
        }
        padson = false;
        popupMetronome_stoporstart = "stop";
        metronomeonoff = "off";
        // Fix buttons
        popupPad_startstopbutton.setText(getResources().getString(R.string.start));
        popupMetronome_startstopbutton.setText(getResources().getString(R.string.start));
        popupAutoscroll_startstopbutton.setText(getResources().getString(R.string.start));
        popupPad_startstopbutton.setEnabled(true);
        popupMetronome_startstopbutton.setEnabled(true);
        popupAutoscroll_startstopbutton.setEnabled(true);
        popupPad_startstopbutton.setBackgroundDrawable(getResources().getDrawable(R.drawable.blue_button));
    }
    if (isPDF && padson) {
        mKey = "";
        padson = false;
        if (mtask_fadeout_music1 != null) {
            mtask_fadeout_music1 = null;
        }
        if (mtask_fadeout_music2 != null) {
            mtask_fadeout_music2 = null;
        }
        fadeout1 = false;
        fadeout2 = false;
        if (mPlayer1 != null) {
            // We need to fade out mPlayer1
            if (mPlayer1.isPlaying()) {
                // We need to fade this out over the next 8 seconds
                //whichtofadeout = 1;
                fadeout1 = true;
                fadeOutBackgroundMusic1();
            }
        }
        if (mPlayer2 != null) {
            // We need to fade out mPlayer2
            if (mPlayer2.isPlaying()) {
                // We need to fade this out over the next 8 seconds
                //whichtofadeout = 2;
                fadeout2 = true;
                fadeOutBackgroundMusic2();
            }
        }
        if (popupPad.getVisibility() != View.VISIBLE) {
            padButton.setAlpha(0.4f);
        }
    }
    // Now, decide which column we are writing to
    if (columnTest == 1) {
        scrollpage = scrollpage_onecol;
        mycolview = linearLayout_onecolview;
    } else if (columnTest == 2) {
        scrollpage = scrollpage_twocol;
        mycolview = linearLayout_twocolview;
    } else if (columnTest == 3) {
        scrollpage = scrollpage_threecol;
        mycolview = linearLayout_threecolview;
    } else {
        scrollpage = scrollpage_onecol;
        mycolview = linearLayout_onecolview;
    }
    if (isPDF) {
        scrollpage = scrollpage_pdf;
        needtoredraw = false;
        columnTest = 99;
    }
    // Set the default view!  Set the theme colours
    SetUpColours.colours();
    main_page.setBackgroundColor(lyricsBackgroundColor);
    scrollpage.setBackgroundColor(lyricsBackgroundColor);
    // Set up a listener to wait for the tables to draw
    ViewTreeObserver vto = scrollpage.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        @SuppressWarnings("SuspiciousNameCombination")
        @Override
        public void onGlobalLayout() {
            scrollpage.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            int width;
            int height;
            pageWidth = main_page.getMeasuredWidth();
            pageHeight = main_page.getMeasuredHeight();
            // Get the scale for 1 col view
            width = lyricstable_onecolview.getMeasuredWidth() + 8;
            height = lyricstable_onecolview.getMeasuredHeight() + 8;
            scaleX = pageWidth / width;
            scaleY = pageHeight / height;
            float override_onecolfontsize = scaleX;
            if (toggleYScale.equals("Y")) {
                if (scaleX > scaleY) {
                    //noinspection SuspiciousNameCombination
                    scaleX = scaleY;
                }
            } else if (toggleYScale.equals("W")) {
                Log.d("d", "Help page found");
                scaleY = scaleX;
            }
            if (songfilename.equals("Welcome to OpenSongApp")) {
                scaleY = scaleX;
            }
            onecolfontsize = scaleX;
            // Get the scale for 2 col view
            width = lyricstable_twocolview.getMeasuredWidth() + lyricstable2_twocolview.getMeasuredWidth() + 16;
            height = lyricstable_twocolview.getMeasuredHeight() + 8;
            int height2 = lyricstable2_twocolview.getMeasuredHeight() + 8;
            if (height2 > height) {
                height = height2;
            }
            scaleX = pageWidth / width;
            scaleY = pageHeight / height;
            if (toggleYScale.equals("Y") && !songfilename.equals("Welcome to OpenSongApp")) {
                if (scaleX > scaleY) {
                    scaleX = pageHeight / height;
                }
            } else if (toggleYScale.equals("W") && !songfilename.equals("Welcome to OpenSongApp")) {
                Log.d("d", "Help page found");
                scaleY = pageWidth / width;
            }
            twocolfontsize = scaleX;
            // Get the scale for 3 col view
            width = lyricstable_threecolview.getMeasuredWidth() + lyricstable2_threecolview.getMeasuredWidth() + lyricstable3_threecolview.getMeasuredWidth() + 36;
            height = lyricstable_threecolview.getMeasuredHeight() + 12;
            height2 = lyricstable2_threecolview.getMeasuredHeight() + 12;
            int height3 = lyricstable3_threecolview.getMeasuredHeight() + 12;
            if (height2 > height) {
                height = height2;
            }
            if (height3 > height) {
                height = height3;
            }
            scaleX = pageWidth / width;
            scaleY = pageHeight / height;
            if (toggleYScale.equals("Y") && !songfilename.equals("Welcome to OpenSongApp")) {
                if (scaleX > scaleY) {
                    scaleX = pageHeight / height;
                }
            } else if (toggleYScale.equals("W") && !songfilename.equals("Welcome to OpenSongApp")) {
                Log.d("d", "Help page found");
                scaleY = pageWidth / width;
            }
            threecolfontsize = scaleX;
            // Which view ia the best one then?  Save the font scale size
            if (threecolfontsize > onecolfontsize && threecolfontsize > twocolfontsize) {
                // 3 columns is best
                tempfontsize = mainfontsize * threecolfontsize - 0.6f;
                tempsectionsize = sectionfontsize * threecolfontsize - 0.6f;
                scrollpage = scrollpage_threecol;
                mycolview = linearLayout_threecolview;
                columnTest = 3;
            } else if (twocolfontsize > onecolfontsize && twocolfontsize > threecolfontsize) {
                tempfontsize = mainfontsize * twocolfontsize - 0.6f;
                tempsectionsize = sectionfontsize * twocolfontsize - 0.6f;
                scrollpage = scrollpage_twocol;
                mycolview = linearLayout_twocolview;
                columnTest = 2;
            } else {
                tempfontsize = mainfontsize * onecolfontsize - 0.6f;
                tempsectionsize = sectionfontsize * onecolfontsize - 0.6f;
                scrollpage = scrollpage_onecol;
                mycolview = linearLayout_onecolview;
                columnTest = 1;
            }
            if (songfilename.equals("Welcome to OpenSongApp")) {
                tempfontsize = mainfontsize * onecolfontsize - 0.6f;
                tempsectionsize = sectionfontsize * onecolfontsize - 0.6f;
                scrollpage = scrollpage_onecol;
                columnTest = 1;
            }
            myToastMessage = "";
            // If the font size is below the minimum font size, and the user has decided to override full scale
            if (tempfontsize < mMinFontSize && toggleYScale.equals("Y") && override_fullscale) {
                myToastMessage = getString(R.string.toastmessage_minfont);
                myToastMessage += "\n" + getString(R.string.override_fullautoscale);
                //myToastMessage += "\n"+getString(R.string.minfontsize)+": "+mMinFontSize+" sp";
                //myToastMessage += "\n"+getString(R.string.size)+": "+(float)((int)(tempfontsize*10))/10.0f+" sp";
                tempfontsize = mainfontsize * override_onecolfontsize - 0.6f;
                tempsectionsize = sectionfontsize * override_onecolfontsize - 0.6f;
                scrollpage = scrollpage_onecol;
                columnTest = 1;
            }
            // If the font size is still below the minimum font size, and the user has decided to override full scale
            if (tempfontsize < mMinFontSize && (toggleYScale.equals("Y") || toggleYScale.equals("W")) && override_widthscale) {
                myToastMessage = getString(R.string.toastmessage_minfont);
                myToastMessage += "\n" + getString(R.string.override_widthautoscale);
                //myToastMessage += "\n"+getString(R.string.minfontsize)+": "+mMinFontSize+" sp";
                //myToastMessage += "\n"+getString(R.string.size)+": "+(float)((int)(tempfontsize*10))/10.0f+" sp";
                tempfontsize = mFontSize;
                tempsectionsize = mFontSize * 0.7f;
                columnTest = 1;
                scrollpage = scrollpage_onecol;
                columnTest = 1;
            }
            ShowToast.showToast(FullscreenActivity.this);
            // Make sure font sizes don't exceed the max specified by the user
            if (mMaxFontSize < 20) {
                mMaxFontSize = 20;
            }
            if (tempfontsize > mMaxFontSize) {
                tempfontsize = mMaxFontSize;
            }
            if (tempsectionsize > mMaxFontSize) {
                tempsectionsize = mMaxFontSize * 0.7f;
            }
            if (toggleYScale.equals("N")) {
                tempfontsize = mFontSize;
                tempsectionsize = mFontSize * 0.7f;
                scrollpage = scrollpage_onecol;
                columnTest = 1;
            }
            needtoredraw = false;
            if (!isPDF) {
                writeSongToPage();
            } else {
                columnTest = 99;
                scrollpage = scrollpage_pdf;
            }
            tempfontsize = mainfontsize;
            tempsectionsize = sectionfontsize;
            songTitleHolder.setTextColor(lyricsTextColor);
            songTitleHolder.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fadeout));
            songLoadingProgressBar.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fadeout));
            songLoadingProgressBar.setVisibility(View.INVISIBLE);
            songTitleHolder.setVisibility(View.INVISIBLE);
            if (whichDirection.equals("L2R")) {
                scrollpage.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_in_left));
            } else {
                scrollpage.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_in_right));
            }
            if (columnTest == 1) {
                scrollpage_onecol.setVisibility(View.VISIBLE);
                scrollpage_pdf.setVisibility(View.GONE);
                scrollpage_twocol.setVisibility(View.GONE);
                scrollpage_threecol.setVisibility(View.GONE);
            } else if (columnTest == 2) {
                scrollpage_twocol.setVisibility(View.VISIBLE);
                scrollpage_pdf.setVisibility(View.GONE);
                scrollpage_onecol.setVisibility(View.GONE);
                scrollpage_threecol.setVisibility(View.GONE);
            } else if (columnTest == 3) {
                scrollpage_threecol.setVisibility(View.VISIBLE);
                scrollpage_pdf.setVisibility(View.GONE);
                scrollpage_onecol.setVisibility(View.GONE);
                scrollpage_twocol.setVisibility(View.GONE);
            } else {
                scrollpage_pdf.setVisibility(View.VISIBLE);
                scrollpage_onecol.setVisibility(View.GONE);
                scrollpage_twocol.setVisibility(View.GONE);
                scrollpage_threecol.setVisibility(View.GONE);
            }
            // If autoStickyNotes is set to yes and they aren't empty, display them
            if (toggleAutoSticky.equals("Y") && !mNotes.isEmpty() && !mNotes.equals("")) {
                // Opening a sticky note!
                // Hide other popups
                hidepopupPad();
                hidepopupChord();
                hidepopupAutoscroll();
                hidepopupMetronome();
                mySticky.setText(mNotes);
                mySticky.setVisibility(View.VISIBLE);
                scrollstickyholder.setVisibility(View.VISIBLE);
                scrollstickyholder.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_in_bottom));
                stickynotes.setAlpha(0.7f);
            }
            // Get the autoscroll info initialised
            if (autostartautoscroll && autoscrollactivated) {
                if (usingdefaults) {
                    myToastMessage = getString(R.string.default_autoscroll);
                    ShowToast.showToast(FullscreenActivity.this);
                }
                if (mtask_autoscroll_music != null) {
                    mtask_autoscroll_music.cancel(true);
                }
                if (delayautoscroll != null && autoScrollRunnable != null) {
                    delayautoscroll.removeCallbacks(autoScrollRunnable);
                }
                autoScrollDelay = popupAutoscroll_delay.getProgress() - 1;
                if (popupAutoscroll_duration.getText() != null) {
                    mDuration = popupAutoscroll_duration.getText().toString();
                } else {
                    mDuration = "";
                }
                getAutoScrollValues();
                // Wait 2 seconds before starting autoscroll (time for page to draw)
                Handler prepareAutoscroll = new Handler();
                prepareAutoscroll.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        popupAutoscroll_startstop(autoscrollButton);
                        Log.d("d", "attempting to start autoscroll");
                    }
                }, 2000);
            }
        }
    });
    if (!isPDF) {
        // Set a variable to decide if capo chords should be shown
        showCapo = !capoDisplay.equals("native") && (mCapo.equals("1") || mCapo.equals("2") || mCapo.equals("3") || mCapo.equals("4") || mCapo.equals("5") || mCapo.equals("6") || mCapo.equals("7") || mCapo.equals("8") || mCapo.equals("9") || mCapo.equals("10") || mCapo.equals("11"));
        // Decide on the font being used
        SetTypeFace.setTypeface();
        // Write the song to the tables
        columnTest = 0;
        writeSongToPage();
        songandauthor.setText("");
        // Decide on best title
        String songtitleorfilename;
        if (mTitle != null && !mTitle.equals("")) {
            songtitleorfilename = mTitle.toString();
        } else {
            songtitleorfilename = songfilename;
        }
        // If key is set
        String keytext = "";
        if (!mKey.isEmpty() && !mKey.equals("")) {
            keytext = " (" + mKey + ")";
        }
        // Get best author
        if (mAuthor != null && !mAuthor.equals("")) {
            mTempAuthor = mAuthor.toString();
        } else {
            mTempAuthor = "";
        }
        // Put the title together
        String text = songtitleorfilename + keytext + "\n" + mTempAuthor;
        songandauthor.setText(text);
    } else {
        Preferences.savePreferences();
        // is a pdf file
        // if we are able, render pdf to image
        // filePath represent path of Pdf document on storage
        File file;
        if (whichSongFolder.equals(mainfoldername)) {
            file = new File(dir + "/" + songfilename);
        } else {
            file = new File(dir + "/" + whichSongFolder + "/" + songfilename);
        }
        String tempsongtitle = songfilename.replace(".pdf", "");
        tempsongtitle = tempsongtitle.replace(".PDF", "");
        mTitle = tempsongtitle;
        mAuthor = "";
        // FileDescriptor for file, it allows you to close file when you are
        // done with it
        ParcelFileDescriptor mFileDescriptor = null;
        try {
            mFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // Capable of pdf rendering
            // PdfRenderer enables rendering a PDF document
            padButton.setVisibility(View.INVISIBLE);
            stickynotes.setVisibility(View.INVISIBLE);
            metronomeButton.setVisibility(View.INVISIBLE);
            autoscrollButton.setVisibility(View.INVISIBLE);
            chordButton.setVisibility(View.INVISIBLE);
            scrollstickyholder.setVisibility(View.GONE);
            PdfRenderer mPdfRenderer = null;
            try {
                if (mFileDescriptor != null) {
                    mPdfRenderer = new PdfRenderer(mFileDescriptor);
                    pdfPageCount = mPdfRenderer.getPageCount();
                }
            } catch (IOException e) {
                e.printStackTrace();
                pdfPageCount = 0;
            }
            if (pdfPageCurrent >= pdfPageCount) {
                pdfPageCurrent = 0;
            }
            String text = tempsongtitle + "\n" + (pdfPageCurrent + 1) + "/" + pdfPageCount;
            songandauthor.setText(text);
            if (pdfPageCount > 1 && togglePageButtons.equals("Y")) {
                // Show page select button
                pdf_selectpage.setVisibility(View.VISIBLE);
            } else {
                pdf_selectpage.setVisibility(View.INVISIBLE);
            }
            stickynotes.setVisibility(View.INVISIBLE);
            scrollstickyholder.setVisibility(View.GONE);
            stickynotes.setAlpha(0.4f);
            // Open page 0
            PdfRenderer.Page mCurrentPage = null;
            if (mPdfRenderer != null) {
                //noinspection AndroidLintNewApi
                mCurrentPage = mPdfRenderer.openPage(pdfPageCurrent);
            }
            // Get pdf size from page
            int pdfwidth;
            int pdfheight;
            if (mCurrentPage != null) {
                pdfwidth = mCurrentPage.getWidth();
                pdfheight = mCurrentPage.getHeight();
            } else {
                pdfwidth = 1;
                pdfheight = 1;
            }
            int holderwidth = pdfwidth;
            int holderheight = pdfheight;
            int pagewidth = main_page.getWidth();
            int pageheight = main_page.getHeight();
            String temptoggle = toggleYScale;
            if (songfilename.equals("Welcome to OpenSongApp")) {
                temptoggle = "W";
            }
            switch(temptoggle) {
                case "Y":
                    float xscale = (float) pagewidth / (float) pdfwidth;
                    float yscale = (float) pageheight / (float) pdfheight;
                    if (xscale > yscale) {
                        xscale = yscale;
                    } else {
                        yscale = xscale;
                    }
                    pdfheight = (int) ((float) pdfheight * yscale);
                    pdfwidth = (int) ((float) pdfwidth * xscale);
                    holderheight = pageheight;
                    holderwidth = pagewidth;
                    break;
                case "W":
                    pdfheight = (int) (((float) pagewidth / (float) pdfwidth) * (float) pdfheight);
                    pdfwidth = pagewidth;
                    holderheight = pdfheight;
                    holderwidth = pdfwidth;
                    break;
                default:
                    // This avoids massive files calling out of memory error
                    if (pdfwidth > pagewidth) {
                        pdfheight = (int) (((float) pagewidth / (float) pdfwidth) * (float) pdfheight);
                        pdfwidth = pagewidth;
                        holderheight = pdfheight;
                        holderwidth = pdfwidth;
                    }
                    break;
            }
            if (pdfwidth == 0) {
                pdfwidth = 1;
            }
            if (pdfheight == 0) {
                pdfheight = 1;
            }
            Bitmap bitmap = Bitmap.createBitmap(pdfwidth, pdfheight, Bitmap.Config.ARGB_8888);
            // Pdf page is rendered on Bitmap
            if (mCurrentPage != null) {
                mCurrentPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
            }
            // Set rendered bitmap to ImageView (pdfView in my case)
            ImageView pdfView = (ImageView) findViewById(R.id.pdfView);
            if (pdfView != null) {
                pdfView.setImageBitmap(bitmap);
                pdfView.getLayoutParams().height = holderheight;
                pdfView.getLayoutParams().width = holderwidth;
            }
            if (mCurrentPage != null) {
                mCurrentPage.close();
            }
            if (mPdfRenderer != null) {
                mPdfRenderer.close();
            }
            if (mFileDescriptor != null) {
                mFileDescriptor.close();
            }
            scrollpage_pdf.scrollTo(0, 0);
            invalidateOptionsMenu();
        } else {
            // Not capable of pdf rendering
            myToastMessage = getResources().getString(R.string.nothighenoughapi);
            ShowToast.showToast(FullscreenActivity.this);
            pdf_selectpage.setVisibility(View.INVISIBLE);
            stickynotes.setVisibility(View.INVISIBLE);
            padButton.setVisibility(View.INVISIBLE);
            chordButton.setVisibility(View.INVISIBLE);
            stickynotes.setVisibility(View.INVISIBLE);
            metronomeButton.setVisibility(View.INVISIBLE);
            autoscrollButton.setVisibility(View.INVISIBLE);
            scrollstickyholder.setVisibility(View.GONE);
            ImageView pdfView = (ImageView) findViewById(R.id.pdfView);
            Drawable myDrawable = getResources().getDrawable(R.drawable.unhappy_android);
            if (pdfView != null) {
                pdfView.setImageDrawable(myDrawable);
                pdfView.getLayoutParams().height = main_page.getHeight();
                pdfView.getLayoutParams().width = main_page.getWidth();
            }
            String text = tempsongtitle + "\n" + getResources().getString(R.string.nothighenoughapi);
            songandauthor.setText(text);
            Preferences.savePreferences();
            invalidateOptionsMenu();
            // Run an intent to try to show the pdf externally
            Intent target = new Intent(Intent.ACTION_VIEW);
            File pdffile;
            if (whichSongFolder.equals(mainfoldername)) {
                pdffile = new File(dir + "/" + songfilename);
            } else {
                pdffile = new File(dir + "/" + whichSongFolder + "/" + songfilename);
            }
            target.setDataAndType(Uri.fromFile(pdffile), "application/pdf");
            target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            try {
                startActivity(target);
            } catch (ActivityNotFoundException e) {
                try {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.google.android.apps.pdfviewer")));
                } catch (ActivityNotFoundException anfe) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.google.android.apps.pdfviewer")));
                }
            }
        }
    }
    FrameLayout.LayoutParams params_fix = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    if (toggleYScale.equals("N") || (toggleYScale.equals("Y") && override_widthscale) || (toggleYScale.equals("W") && override_widthscale)) {
        params_fix.gravity = Gravity.LEFT;
        scrollpage_onecol.scrollTo(0, 0);
        horizontalScrollView1_onecolview.scrollTo(0, 0);
    } else {
        params_fix.gravity = Gravity.CENTER_HORIZONTAL;
    }
    linearLayout2_onecolview.setLayoutParams(params_fix);
    // Only do this if needtoredraw = false;
    if (!needtoredraw) {
        prepareChords();
    }
    // If we have just converted a song from .pro or .onsong, we need to fix the song menu
    if (converting) {
        converting = false;
        prepareSongMenu();
    }
}
Example 7
Project: android-PdfRendererBasic-master  File: PdfRendererBasicFragment.java View source code
/**
     * Sets up a {@link android.graphics.pdf.PdfRenderer} and related resources.
     */
private void openRenderer(Context context) throws IOException {
    // In this sample, we read a PDF from the assets directory.
    File file = new File(context.getCacheDir(), FILENAME);
    if (!file.exists()) {
        // Since PdfRenderer cannot handle the compressed asset file directly, we copy it into
        // the cache directory.
        InputStream asset = context.getAssets().open(FILENAME);
        FileOutputStream output = new FileOutputStream(file);
        final byte[] buffer = new byte[1024];
        int size;
        while ((size = asset.read(buffer)) != -1) {
            output.write(buffer, 0, size);
        }
        asset.close();
        output.close();
    }
    mFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
    // This is the PdfRenderer we use to render the PDF.
    if (mFileDescriptor != null) {
        mPdfRenderer = new PdfRenderer(mFileDescriptor);
    }
}
Example 8
Project: PdfViewPager-master  File: PDFPagerAdapter.java View source code
@Override
@SuppressWarnings("NewApi")
public Object instantiateItem(ViewGroup container, int position) {
    View v = inflater.inflate(R.layout.view_pdf_page, container, false);
    ImageView iv = (ImageView) v.findViewById(R.id.imageView);
    if (renderer == null || getCount() < position) {
        return v;
    }
    PdfRenderer.Page page = getPDFPage(renderer, position);
    Bitmap bitmap = bitmapContainer.get(position);
    page.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
    page.close();
    PhotoViewAttacher attacher = new PhotoViewAttacher(iv);
    attacher.setScale(scale.getScale(), scale.getCenterX(), scale.getCenterY(), true);
    attacher.setOnMatrixChangeListener(this);
    attachers.put(position, new WeakReference<PhotoViewAttacher>(attacher));
    iv.setImageBitmap(bitmap);
    attacher.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {

        @Override
        public void onPhotoTap(View view, float x, float y) {
            pageClickListener.onClick(view);
        }
    });
    attacher.update();
    ((ViewPager) container).addView(v, 0);
    return v;
}
Example 9
Project: android_frameworks_base-master  File: PdfManipulationService.java View source code
@Override
public int openDocument(ParcelFileDescriptor source) throws RemoteException {
    synchronized (mLock) {
        try {
            throwIfOpened();
            if (DEBUG) {
                Log.i(LOG_TAG, "openDocument()");
            }
            mRenderer = new PdfRenderer(source);
            return mRenderer.getPageCount();
        } catch (IOExceptionIllegalStateException |  e) {
            IoUtils.closeQuietly(source);
            Log.e(LOG_TAG, "Cannot open file", e);
            return ERROR_MALFORMED_PDF_FILE;
        } catch (SecurityException e) {
            IoUtils.closeQuietly(source);
            Log.e(LOG_TAG, "Cannot open file", e);
            return ERROR_SECURE_PDF_FILE;
        }
    }
}
Example 10
Project: android-sdk-sources-for-api-level-23-master  File: PdfManipulationService.java View source code
@Override
public int openDocument(ParcelFileDescriptor source) throws RemoteException {
    synchronized (mLock) {
        try {
            throwIfOpened();
            if (DEBUG) {
                Log.i(LOG_TAG, "openDocument()");
            }
            mRenderer = new PdfRenderer(source);
            return mRenderer.getPageCount();
        } catch (IOExceptionIllegalStateException |  e) {
            IoUtils.closeQuietly(source);
            Log.e(LOG_TAG, "Cannot open file", e);
            return ERROR_MALFORMED_PDF_FILE;
        } catch (SecurityException e) {
            IoUtils.closeQuietly(source);
            Log.e(LOG_TAG, "Cannot open file", e);
            return ERROR_SECURE_PDF_FILE;
        }
    }
}