Search in sources :

Example 1 with CodecDocument

use of org.ebookdroid.core.codec.CodecDocument in project LibreraReader by foobnix.

the class PdfExtract method getBookMetaInformation.

public static EbookMeta getBookMetaInformation(String unZipPath) {
    PdfContext codecContex = new PdfContext();
    CodecDocument openDocument = null;
    try {
        openDocument = codecContex.openDocument(unZipPath, "");
    } catch (RuntimeException e) {
        LOG.e(e);
        return EbookMeta.Empty();
    }
    EbookMeta meta = new EbookMeta(openDocument.getBookTitle(), openDocument.getBookAuthor());
    meta.setPagesCount(openDocument.getPageCount());
    if ("untitled".equals(meta.getTitle())) {
        meta.setTitle("");
    }
    LOG.d("PdfExtract", meta.getAuthor(), meta.getTitle(), unZipPath);
    openDocument.recycle();
    openDocument = null;
    return meta;
}
Also used : PdfContext(org.ebookdroid.droids.mupdf.codec.PdfContext) CodecDocument(org.ebookdroid.core.codec.CodecDocument)

Example 2 with CodecDocument

use of org.ebookdroid.core.codec.CodecDocument in project LibreraReader by foobnix.

the class MultyDocSearchDialog method searchInThePDF.

public static int searchInThePDF(String path, String text, final Handler update1) {
    try {
        text = text.toLowerCase(Locale.US);
        CodecContext ctx = BookType.getCodecContextByPath(path);
        CodecDocument openDocument = null;
        CacheZipUtils.cacheLock.lock();
        try {
            String zipPath = CacheZipUtils.extracIfNeed(path, CacheDir.ZipApp).unZipPath;
            openDocument = ctx.openDocument(zipPath, "");
            LOG.d("searchInThePDF", openDocument, zipPath);
        } finally {
            CacheZipUtils.cacheLock.unlock();
        }
        if (!Model.get().isSearcingRun) {
            openDocument.recycle();
            ctx.recycle();
            return -1;
        }
        int pageCount = openDocument.getPageCount();
        Model.get().currentPagesCount = pageCount;
        Model.get().currentDoc = new File(path).getName();
        LOG.d("searchInThePDF", "pageCount", Model.get().currentPagesCount, Model.get().currentDoc);
        int emptyCount = 0;
        for (int i = 0; i < pageCount; i++) {
            if (!Model.get().isSearcingRun) {
                openDocument.recycle();
                ctx.recycle();
                return -1;
            }
            CodecPage page = openDocument.getPage(i);
            TextWord[][] textPage = page.getText();
            LOG.d("searchInThePDF", "getText", textPage != null ? textPage.length : "null");
            if (textPage == null || textPage.length <= 1) {
                emptyCount++;
                if (emptyCount >= 5) {
                    LOG.d("searchInThePDF", "Page is empty", emptyCount);
                    break;
                }
            }
            List<TextWord> findText = Page.findText(text, textPage);
            page.recycle();
            page = null;
            Model.get().currentPage = i;
            update1.sendEmptyMessage(0);
            if (!findText.isEmpty()) {
                openDocument.recycle();
                ctx.recycle();
                findText = null;
                openDocument = null;
                ctx = null;
                return i;
            }
            findText = null;
        }
        openDocument.recycle();
        ctx.recycle();
        openDocument = null;
        ctx = null;
        System.gc();
    } catch (Exception e) {
        LOG.e(e);
    }
    return -1;
}
Also used : CodecContext(org.ebookdroid.core.codec.CodecContext) CodecPage(org.ebookdroid.core.codec.CodecPage) File(java.io.File) TextWord(org.ebookdroid.droids.mupdf.codec.TextWord) CodecDocument(org.ebookdroid.core.codec.CodecDocument)

Example 3 with CodecDocument

use of org.ebookdroid.core.codec.CodecDocument in project LibreraReader by foobnix.

the class ImageExtractor method proccessOtherPage.

public Bitmap proccessOtherPage(PageUrl pageUrl, FileMeta meta) {
    int page = pageUrl.getPage();
    String path = pageUrl.getPath();
    boolean isNeedDisableMagicInPDFDjvu = false;
    LOG.d("Page Number", pageUrl.getPage());
    if (pageUrl.getPage() == COVER_PAGE || pageUrl.getPage() == COVER_PAGE_NO_EFFECT || pageUrl.getPage() == COVER_PAGE_WITH_EFFECT) {
        isNeedDisableMagicInPDFDjvu = true;
    }
    if (page < 0) {
        page = 0;
    }
    if (pageUrl.isCrop()) {
    // isNeedDisableMagicInPDFDjvu = true;
    }
    CodecDocument codeCache = null;
    if (isNeedDisableMagicInPDFDjvu) {
        codeCache = singleCodecContext(path, "", pageUrl.getWidth(), pageUrl.getHeight());
        if (meta != null && codeCache != null && FileMetaCore.isNeedToExtractPDFMeta(path)) {
            String bookAuthor = codeCache.getBookAuthor();
            if (TxtUtils.isNotEmpty(bookAuthor)) {
                meta.setAuthor(bookAuthor);
            }
            String bookTitle = codeCache.getBookTitle();
            if (TxtUtils.isNotEmpty(bookTitle)) {
                meta.setTitle(bookTitle);
            }
            LOG.d("PDF getBookAuthor", bookAuthor, bookTitle);
        }
    } else {
        codeCache = getNewCodecContext(path, "", pageUrl.getWidth(), pageUrl.getHeight());
    }
    if (codeCache == null) {
        LOG.d("TEST", "codecDocument == null" + path);
        return null;
    }
    if (isNeedDisableMagicInPDFDjvu && meta != null) {
        meta.setPages(codeCache.getPageCount());
    }
    final CodecPageInfo pageInfo = codeCache.getPageInfo(page);
    Bitmap bitmap = null;
    RectF rectF = new RectF(0, 0, 1f, 1f);
    final float k = (float) pageInfo.height / pageInfo.width;
    int width = pageUrl.getWidth();
    int height = (int) (width * k);
    LOG.d("Bitmap", width, height);
    LOG.d("Bitmap pageInfo.height", pageInfo.width, pageInfo.height);
    BitmapRef bitmapRef = null;
    CodecPage pageCodec = codeCache.getPage(page);
    if (pageUrl.getNumber() == 0) {
        rectF = new RectF(0, 0, 1f, 1f);
        if (isNeedDisableMagicInPDFDjvu) {
            bitmapRef = pageCodec.renderBitmapSimple(width, height, rectF);
        } else {
            bitmapRef = pageCodec.renderBitmap(width, height, rectF);
        }
        bitmap = bitmapRef.getBitmap();
        if (pageUrl.isCrop()) {
            if (BookType.DJVU.is(pageUrl.getPath())) {
                Bitmap sample = pageCodec.renderBitmapSimple(PageCropper.MAX_WIDTH, PageCropper.MAX_HEIGHT, rectF).getBitmap();
                bitmap = cropBitmap(bitmap, sample);
                sample.recycle();
                sample = null;
            } else {
                bitmap = cropBitmap(bitmap, bitmap);
            }
        }
    } else if (pageUrl.getNumber() == 1) {
        float right = (float) pageUrl.getCutp() / 100;
        rectF = new RectF(0, 0, right, 1f);
        bitmapRef = pageCodec.renderBitmap((int) (width * right), height, rectF);
        bitmap = bitmapRef.getBitmap();
        if (pageUrl.isCrop()) {
            bitmap = cropBitmap(bitmap, bitmap);
        }
    } else if (pageUrl.getNumber() == 2) {
        float right = (float) pageUrl.getCutp() / 100;
        rectF = new RectF(right, 0, 1f, 1f);
        bitmapRef = pageCodec.renderBitmap((int) (width * (1 - right)), height, rectF);
        bitmap = bitmapRef.getBitmap();
        if (pageUrl.isCrop()) {
            bitmap = cropBitmap(bitmap, bitmap);
        }
    }
    if (pageUrl.isInvert()) {
        final RawBitmap bmp = new RawBitmap(bitmap, new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()));
        bmp.invert();
        bitmap.recycle();
        bitmap = bmp.toBitmap().getBitmap();
    }
    if (pageUrl.getRotate() > 0) {
        final Matrix matrix = new Matrix();
        matrix.postRotate(pageUrl.getRotate());
        final Bitmap bitmap1 = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        bitmap.recycle();
        bitmap = bitmap1;
    }
    if (pageUrl.isDoText() && !pageCodec.isRecycled()) {
        PageImageState.get().pagesText.put(pageUrl.getPage(), pageCodec.getText());
        PageImageState.get().pagesLinks.put(pageUrl.getPage(), pageCodec.getPageLinks());
    }
    if (!pageCodec.isRecycled()) {
        pageCodec.recycle();
    }
    if (isNeedDisableMagicInPDFDjvu) {
        codeCache.recycle();
    }
    if (!isNeedDisableMagicInPDFDjvu && MagicHelper.isNeedBookBackgroundImage()) {
        bitmap = MagicHelper.updateWithBackground(bitmap);
    }
    return bitmap;
}
Also used : Rect(android.graphics.Rect) CodecPage(org.ebookdroid.core.codec.CodecPage) RectF(android.graphics.RectF) RawBitmap(org.ebookdroid.common.bitmaps.RawBitmap) Bitmap(android.graphics.Bitmap) Matrix(android.graphics.Matrix) CodecPageInfo(org.ebookdroid.core.codec.CodecPageInfo) RawBitmap(org.ebookdroid.common.bitmaps.RawBitmap) BitmapRef(org.ebookdroid.common.bitmaps.BitmapRef) CodecDocument(org.ebookdroid.core.codec.CodecDocument)

Example 4 with CodecDocument

use of org.ebookdroid.core.codec.CodecDocument in project LibreraReader by foobnix.

the class TTSService method playPage.

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
private void playPage(String preText, int pageNumber, String anchor) {
    if (pageNumber != -1) {
        EventBus.getDefault().post(new MessagePageNumber(pageNumber));
        AppState.get().lastBookPage = pageNumber;
        CodecDocument dc = getDC();
        if (dc == null) {
            LOG.d(TAG, "CodecDocument", "is NULL");
            return;
        }
        int pageCount = dc.getPageCount();
        LOG.d(TAG, "CodecDocument PageCount", pageNumber, pageCount);
        if (pageNumber >= pageCount) {
            TempHolder.get().timerFinishTime = 0;
            Vibro.vibrate(1000);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
            }
            TTSEngine.get().getTTS().setOnUtteranceCompletedListener(null);
            TTSEngine.get().speek(LibreraApp.context.getString(R.string.the_book_is_over));
            EventBus.getDefault().post(new TtsStatus());
            return;
        }
        CodecPage page = dc.getPage(pageNumber);
        String pageHTML = page.getPageHTML();
        page.recycle();
        pageHTML = TxtUtils.replaceHTMLforTTS(pageHTML);
        if (TxtUtils.isNotEmpty(anchor)) {
            int indexOf = pageHTML.indexOf(anchor);
            if (indexOf > 0) {
                pageHTML = pageHTML.substring(indexOf);
                LOG.d("find anchor new text", pageHTML);
            }
        }
        LOG.d(TAG, pageHTML);
        if (TxtUtils.isEmpty(pageHTML)) {
            LOG.d("empty page play next one", emptyPageCount);
            emptyPageCount++;
            if (emptyPageCount < 3) {
                playPage("", AppState.get().lastBookPage + 1, null);
            }
            return;
        }
        emptyPageCount = 0;
        String[] parts = TxtUtils.getParts(pageHTML);
        String firstPart = parts[0];
        final String secondPart = parts[1];
        if (TxtUtils.isNotEmpty(preText)) {
            preText = TxtUtils.replaceLast(preText, "-", "");
            firstPart = preText + firstPart;
        }
        if (Build.VERSION.SDK_INT >= 15) {
            TTSEngine.get().getTTS().setOnUtteranceProgressListener(new UtteranceProgressListener() {

                @Override
                public void onStart(String utteranceId) {
                }

                @Override
                public void onError(String utteranceId) {
                    TTSEngine.get().stop();
                }

                @Override
                public void onDone(String utteranceId) {
                    LOG.d(TAG, "onUtteranceCompleted");
                    if (TempHolder.get().timerFinishTime != 0 && System.currentTimeMillis() > TempHolder.get().timerFinishTime) {
                        LOG.d(TAG, "Timer");
                        TempHolder.get().timerFinishTime = 0;
                        return;
                    }
                    playPage(secondPart, AppState.get().lastBookPage + 1, null);
                    SettingsManager.updateTempPage(AppState.get().lastBookPath, AppState.get().lastBookPage + 1);
                }
            });
        } else {
            TTSEngine.get().getTTS().setOnUtteranceCompletedListener(new OnUtteranceCompletedListener() {

                @Override
                public void onUtteranceCompleted(String utteranceId) {
                    LOG.d(TAG, "onUtteranceCompleted");
                    if (TempHolder.get().timerFinishTime != 0 && System.currentTimeMillis() > TempHolder.get().timerFinishTime) {
                        LOG.d(TAG, "Timer");
                        TempHolder.get().timerFinishTime = 0;
                        return;
                    }
                    playPage(secondPart, AppState.get().lastBookPage + 1, null);
                    SettingsManager.updateTempPage(AppState.get().lastBookPath, AppState.get().lastBookPage + 1);
                }
            });
        }
        TTSNotification.show(AppState.get().lastBookPath, pageNumber + 1);
        TTSEngine.get().speek(firstPart);
        EventBus.getDefault().post(new TtsStatus());
        savePage();
    }
}
Also used : OnUtteranceCompletedListener(android.speech.tts.TextToSpeech.OnUtteranceCompletedListener) UtteranceProgressListener(android.speech.tts.UtteranceProgressListener) CodecPage(org.ebookdroid.core.codec.CodecPage) CodecDocument(org.ebookdroid.core.codec.CodecDocument) TargetApi(android.annotation.TargetApi)

Example 5 with CodecDocument

use of org.ebookdroid.core.codec.CodecDocument in project LibreraReader by foobnix.

the class ExtUtils method openPDFInTextReflowAsync.

public static File openPDFInTextReflowAsync(Activity a, final File file, Handler dialog) {
    try {
        File bookTempRoot = new File(AppState.get().downlodsPath, file.getName());
        if (!bookTempRoot.exists()) {
            bookTempRoot.mkdirs();
        } else {
            CacheZipUtils.removeFiles(bookTempRoot.listFiles());
        }
        String pwd = "";
        try {
            pwd = a.getIntent().getStringExtra(HorizontalModeController.EXTRA_PASSWORD);
            if (pwd == null) {
                pwd = "";
            }
        } catch (Exception e) {
            LOG.e(e);
        }
        CodecDocument doc = BookType.getCodecContextByPath(file.getPath()).openDocument(file.getPath(), pwd);
        List<OutlineLink> outline = doc.getOutline();
        final File fileReflowHtml = new File(bookTempRoot, "temp" + REFLOW_HTML);
        try {
            FileWriter fout = new FileWriter(fileReflowHtml);
            BufferedWriter out = new BufferedWriter(fout);
            out.write("<html>");
            out.write("<head><meta charset=\"utf-8\"/></head>");
            out.write("<body>");
            int pages = doc.getPageCount();
            int imgCount = 0;
            for (int i = 0; i < pages; i++) {
                LOG.d("Extract page", i);
                CodecPage pageCodec = doc.getPage(i);
                String html = pageCodec.getPageHTMLWithImages();
                out.write("<a id=\"" + i + "\"></a>");
                html = TxtUtils.replaceEndLine(html);
                int startImage = html.indexOf(IMAGE_BEGIN);
                while (startImage >= 0) {
                    if (!TempHolder.get().isConverting) {
                        CacheZipUtils.removeFiles(bookTempRoot.listFiles());
                        bookTempRoot.delete();
                        break;
                    }
                    imgCount++;
                    LOG.d("Extract image", imgCount);
                    int endImage = html.indexOf(IMAGE_END, startImage);
                    String mime = html.substring(startImage + IMAGE_BEGIN.length(), endImage);
                    String format;
                    if (mime.startsWith(IMAGE_JPEG_BASE64)) {
                        format = ".jpg";
                        mime = mime.replace(IMAGE_JPEG_BASE64, "");
                    } else if (mime.startsWith(IMAGE_PNG_BASE64)) {
                        format = ".png";
                        mime = mime.replace(IMAGE_PNG_BASE64, "");
                    } else {
                        format = ".none";
                    }
                    // FileOutputStream mimeOut = new FileOutputStream(new File(bookTempRoot, "mime"
                    // + imgCount + ".mime"));
                    // mimeOut.write(mime.getBytes());
                    // mimeOut.close();
                    byte[] decode = Base64.decode(mime, Base64.DEFAULT);
                    String imageName = imgCount + format;
                    LOG.d("Extract-mime", mime.substring(mime.length() - 10, mime.length()));
                    FileOutputStream imgStream = new FileOutputStream(new File(bookTempRoot, imageName));
                    imgStream.write(decode);
                    imgStream.close();
                    html = html.substring(0, startImage) + "<img src=\"" + imageName + "\"/>" + html.substring(endImage + IMAGE_END.length());
                    startImage = html.indexOf(IMAGE_BEGIN);
                    LOG.d("startImage", startImage);
                }
                // out.write(TextUtils.htmlEncode(html));
                // html = html.replace("< ", "&lt; ");
                // html = html.replace("> ", "&gt; ");
                // html = html.replace("&", "&amp;");
                out.write(html);
                pageCodec.recycle();
                LOG.d("Extract page end1", i);
                dialog.sendEmptyMessage(((i + 1) * 100) / pages);
                if (!TempHolder.get().isConverting) {
                    CacheZipUtils.removeFiles(bookTempRoot.listFiles());
                    bookTempRoot.delete();
                    break;
                }
            }
            doc.recycle();
            out.write("</body></html>");
            out.flush();
            out.close();
            fout.close();
        } catch (Exception e) {
            LOG.e(e);
            return null;
        }
        File epubOutpub = new File(AppState.get().downlodsPath, file.getName() + REFLOW_EPUB);
        if (epubOutpub.isFile()) {
            epubOutpub.delete();
        }
        FileMeta meta = AppDB.get().getOrCreate(file.getPath());
        Fb2Extractor.convertFolderToEpub(bookTempRoot, epubOutpub, meta.getAuthor(), meta.getTitle(), outline);
        CacheZipUtils.removeFiles(bookTempRoot.listFiles());
        bookTempRoot.delete();
        if (!TempHolder.get().isConverting) {
            epubOutpub.delete();
            LOG.d("Delete temp file", fileReflowHtml.getPath());
        }
        LOG.d("openPDFInTextReflow", fileReflowHtml.getPath());
        return epubOutpub;
    } catch (RuntimeException e) {
        LOG.e(e);
        return null;
    }
}
Also used : OutlineLink(org.ebookdroid.core.codec.OutlineLink) FileWriter(java.io.FileWriter) CodecPage(org.ebookdroid.core.codec.CodecPage) BufferedWriter(java.io.BufferedWriter) FileOutputStream(java.io.FileOutputStream) File(java.io.File) FileMeta(com.foobnix.dao2.FileMeta) CodecDocument(org.ebookdroid.core.codec.CodecDocument)

Aggregations

CodecDocument (org.ebookdroid.core.codec.CodecDocument)6 CodecPage (org.ebookdroid.core.codec.CodecPage)4 File (java.io.File)3 FileMeta (com.foobnix.dao2.FileMeta)2 TargetApi (android.annotation.TargetApi)1 AlertDialog (android.app.AlertDialog)1 DialogInterface (android.content.DialogInterface)1 OnDismissListener (android.content.DialogInterface.OnDismissListener)1 Bitmap (android.graphics.Bitmap)1 Matrix (android.graphics.Matrix)1 Rect (android.graphics.Rect)1 RectF (android.graphics.RectF)1 OnUtteranceCompletedListener (android.speech.tts.TextToSpeech.OnUtteranceCompletedListener)1 UtteranceProgressListener (android.speech.tts.UtteranceProgressListener)1 View (android.view.View)1 OnClickListener (android.view.View.OnClickListener)1 ImageView (android.widget.ImageView)1 TextView (android.widget.TextView)1 ScaledImageView (com.foobnix.pdf.info.view.ScaledImageView)1 AppBookmark (com.foobnix.pdf.info.wrapper.AppBookmark)1