主頁 > 移動端開發 > Qt在Android平臺上實作html轉PDF的功能

Qt在Android平臺上實作html轉PDF的功能

2020-09-15 20:50:46 移動端開發

Qt for Android

Qt for Android enables you to run Qt 5 applications Android devices. All Qt modules (essential and add-on) are supported except Qt WebEngine, Qt Serial Port, and the platform-specific ones (Qt Mac Extras, Qt Windows Extras, and Qt X11 Extras).

 

在Windows或者Linux平臺上可以用QtWebEngine模塊實作網頁預覽和列印成PDF檔案,用起來很方便,生成的檔案質量也比較好,但在Android平臺上QtWebEngine模塊不能用,想要顯示網頁可以用QtWebView模塊,不支持列印成PDF,嘗試用QTextDocument和QPrinter將html轉為PDF,發現QTextDocument不支持CSS樣式,生成的PDF檔案排版是錯的,

 

查看QtWebView在Android平臺上的實作,可以發現其用的就是Android的WebView控制元件實作的網頁顯示,嘗試在Android平臺上實作html生成PDF,找到了這篇文章https://www.jianshu.com/p/d82bd61b11a4,驗證后可行,需要依賴第三方庫DexMaker,可以用谷歌實作的 implementation 'com.google.dexmaker:dexmaker:1.2',庫檔案名為dexmaker-1.2.jar,

 

修改QT原始碼,在Android平臺上實作html轉PDF的功能

  • 修改$QtSrc/qtwebview/src/jar/src/org/qtproject/qt5/android/view/QtAndroidWebViewController.java檔案
    /****************************************************************************
    **
    ** Copyright (C) 2015 The Qt Company Ltd.
    ** Contact: http://www.qt.io/licensing/
    **
    ** This file is part of the QtWebView module of the Qt Toolkit.
    **
    ** $QT_BEGIN_LICENSE:LGPL3$
    ** Commercial License Usage
    ** Licensees holding valid commercial Qt licenses may use this file in
    ** accordance with the commercial license agreement provided with the
    ** Software or, alternatively, in accordance with the terms contained in
    ** a written agreement between you and The Qt Company. For licensing terms
    ** and conditions see http://www.qt.io/terms-conditions. For further
    ** information use the contact form at http://www.qt.io/contact-us.
    **
    ** GNU Lesser General Public License Usage
    ** Alternatively, this file may be used under the terms of the GNU Lesser
    ** General Public License version 3 as published by the Free Software
    ** Foundation and appearing in the file LICENSE.LGPLv3 included in the
    ** packaging of this file. Please review the following information to
    ** ensure the GNU Lesser General Public License version 3 requirements
    ** will be met: https://www.gnu.org/licenses/lgpl.html.
    **
    ** GNU General Public License Usage
    ** Alternatively, this file may be used under the terms of the GNU
    ** General Public License version 2.0 or later as published by the Free
    ** Software Foundation and appearing in the file LICENSE.GPL included in
    ** the packaging of this file. Please review the following information to
    ** ensure the GNU General Public License version 2.0 requirements will be
    ** met: http://www.gnu.org/licenses/gpl-2.0.html.
    **
    ** $QT_END_LICENSE$
    **
    ****************************************************************************/
    
    package org.qtproject.qt5.android.view;
    
    import android.content.pm.PackageManager;
    import android.view.View;
    import android.webkit.GeolocationPermissions;
    import android.webkit.URLUtil;
    import android.webkit.ValueCallback;
    import android.annotation.SuppressLint;
    import android.content.Context;
    import android.os.Bundle;
    import android.os.CancellationSignal;
    import android.os.ParcelFileDescriptor;
    import android.print.PageRange;
    import android.print.PrintAttributes;
    import android.print.PrintDocumentAdapter;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;
    import android.webkit.WebChromeClient;
    
    import java.lang.Runnable;
    
    import android.app.Activity;
    import android.content.Intent;
    import android.net.Uri;
    
    import java.lang.String;
    
    import android.webkit.WebSettings;
    import android.webkit.WebSettings.PluginState;
    import android.graphics.Bitmap;
    
    import java.util.concurrent.Semaphore;
    import java.io.File;
    import java.io.IOException;
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    
    import android.os.Build;
    
    import java.util.concurrent.TimeUnit;
    
    import com.google.dexmaker.stock.ProxyBuilder;
    
    public class QtAndroidWebViewController
    {
        private final Activity m_activity;
        private final long m_id;
        private boolean busy;
        private boolean m_hasLocationPermission;
        private WebView m_webView = null;
        private static final String TAG = "QtAndroidWebViewController";
        private final int INIT_STATE = 0;
        private final int STARTED_STATE = 1;
        private final int LOADING_STATE = 2;
        private final int FINISHED_STATE = 3;
    
        private volatile int m_loadingState = INIT_STATE;
        private volatile int m_progress = 0;
        private volatile int m_frameCount = 0;
    
        // API 11 methods
        private Method m_webViewOnResume = null;
        private Method m_webViewOnPause = null;
        private Method m_webSettingsSetDisplayZoomControls = null;
    
        // API 19 methods
        private Method m_webViewEvaluateJavascript = null;
    
        // Native callbacks
        private native void c_onPageFinished(long id, String url);
        private native void c_onPageStarted(long id, String url, Bitmap icon);
        private native void c_onProgressChanged(long id, int newProgress);
        private native void c_onReceivedIcon(long id, Bitmap icon);
        private native void c_onReceivedTitle(long id, String title);
        private native void c_onRunJavaScriptResult(long id, long callbackId, String result);
        private native void c_onReceivedError(long id, int errorCode, String description, String url);
        private native void c_onpdfPrintingFinished(long id, boolean succeed);
    
        // We need to block the UI thread in some cases, if it takes to long we should timeout before
        // ANR kicks in... Usually the hard limit is set to 10s and if exceed that then we're in trouble.
        // In general we should not let input events be delayed for more then 500ms (If we're spending more
        // then 200ms somethings off...).
        private final long BLOCKING_TIMEOUT = 250;
    
        private void resetLoadingState(final int state)
        {
            m_progress = 0;
            m_frameCount = 0;
            m_loadingState = state;
        }
    
        private class Html2Pdf {
            private File file;
            private File dexCacheFile;
            private PrintDocumentAdapter printAdapter;
            private PageRange[] ranges;
            private ParcelFileDescriptor descriptor;
        
            private void printToPdf(WebView webView, String fileName) {
                if (webView != null) {
                    file = new File(fileName);
                    dexCacheFile = webView.getContext().getDir("dex", 0);
                    if (!dexCacheFile.exists()) {
                        dexCacheFile.mkdir();
                    }
                    try {
                        if (file.exists()) {
                            file.delete();
                        }
                        file.createNewFile();
                        descriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_WRITE);
                        PrintAttributes attributes = new PrintAttributes.Builder()
                                .setMediaSize(PrintAttributes.MediaSize.ISO_A4)
                                .setResolution(new PrintAttributes.Resolution("id", Context.PRINT_SERVICE, 300, 300))
                                .setColorMode(PrintAttributes.COLOR_MODE_COLOR)
                                .setMinMargins(PrintAttributes.Margins.NO_MARGINS)
                                .build();
                        ranges = new PageRange[]{PageRange.ALL_PAGES};
        
                        printAdapter = webView.createPrintDocumentAdapter();
                        printAdapter.onStart();
                        printAdapter.onLayout(attributes, attributes, new CancellationSignal(), getLayoutResultCallback(new InvocationHandler() {
                            @Override
                            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                                if (method.getName().equals("onLayoutFinished")) {
                                    onLayoutSuccess();
                                } else {
                                    descriptor.close();
                                    c_onpdfPrintingFinished(m_id, false);
                                    busy = false;
                                }
                                return null;
                            }
                        }, dexCacheFile.getAbsoluteFile()), new Bundle());
                    } catch (IOException e) {
                        if (descriptor != null) {
                            try {
                                descriptor.close();
                            } catch (IOException ex) {
                                ex.printStackTrace();
                            }
                        }
                        c_onpdfPrintingFinished(m_id, false);
                        e.printStackTrace();
                        busy = false;
                    }
                }
            }
        
            private void onLayoutSuccess() throws IOException {
                PrintDocumentAdapter.WriteResultCallback callback = getWriteResultCallback(new InvocationHandler() {
                    @Override
                    public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                        if (method.getName().equals("onWriteFinished")) {
                            c_onpdfPrintingFinished(m_id, true);
                        } else {
                            c_onpdfPrintingFinished(m_id, false);
                        }
                        busy = false;
                        if (descriptor != null) {
                            try {
                                descriptor.close();
                            } catch (IOException ex) {
                                ex.printStackTrace();
                            }
                        }
                        return null;
                    }
                }, dexCacheFile.getAbsoluteFile());
                printAdapter.onWrite(ranges, descriptor, new CancellationSignal(), callback);
            }
        
            @SuppressLint("NewApi")
            private  PrintDocumentAdapter.LayoutResultCallback getLayoutResultCallback(InvocationHandler invocationHandler, File dexCacheDir) throws IOException {
                return ProxyBuilder.forClass(PrintDocumentAdapter.LayoutResultCallback.class)
                        .dexCache(dexCacheDir)
                        .handler(invocationHandler)
                        .build();
            }
        
            @SuppressLint("NewApi")
            private  PrintDocumentAdapter.WriteResultCallback getWriteResultCallback(InvocationHandler invocationHandler, File dexCacheDir) throws IOException {
                return ProxyBuilder.forClass(PrintDocumentAdapter.WriteResultCallback.class)
                        .dexCache(dexCacheDir)
                        .handler(invocationHandler)
                        .build();
            }    
        }
    
        private class QtAndroidWebViewClient extends WebViewClient
        {
            QtAndroidWebViewClient() { super(); }
    
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
                // handle http: and http:, etc., as usual
                if (URLUtil.isValidUrl(url))
                    return false;
    
                // try to handle geo:, tel:, mailto: and other schemes
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    view.getContext().startActivity(intent);
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
    
                return false;
            }
    
            @Override
            public void onl oadResource(WebView view, String url)
            {
                super.onLoadResource(view, url);
            }
    
            @Override
            public void onPageFinished(WebView view, String url)
            {
                super.onPageFinished(view, url);
                m_loadingState = FINISHED_STATE;
                if (m_progress != 100) // onProgressChanged() will notify Qt if we didn't finish here.
                    return;
    
                 m_frameCount = 0;
                 c_onPageFinished(m_id, url);
            }
    
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon)
            {
                super.onPageStarted(view, url, favicon);
                if (++m_frameCount == 1) { // Only call onPageStarted for the first frame.
                    m_loadingState = LOADING_STATE;
                    c_onPageStarted(m_id, url, favicon);
                }
            }
    
            @Override
            public void onReceivedError(WebView view,
                                        int errorCode,
                                        String description,
                                        String url)
            {
                super.onReceivedError(view, errorCode, description, url);
                resetLoadingState(INIT_STATE);
                c_onReceivedError(m_id, errorCode, description, url);
            }
        }
    
        private class QtAndroidWebChromeClient extends WebChromeClient
        {
            QtAndroidWebChromeClient() { super(); }
            @Override
            public void onProgressChanged(WebView view, int newProgress)
            {
                super.onProgressChanged(view, newProgress);
                m_progress = newProgress;
                c_onProgressChanged(m_id, newProgress);
                if (m_loadingState == FINISHED_STATE && m_progress == 100) { // Did we finish?
                    m_frameCount = 0;
                    c_onPageFinished(m_id, view.getUrl());
                }
            }
    
            @Override
            public void onReceivedIcon(WebView view, Bitmap icon)
            {
                super.onReceivedIcon(view, icon);
                c_onReceivedIcon(m_id, icon);
            }
    
            @Override
            public void onReceivedTitle(WebView view, String title)
            {
                super.onReceivedTitle(view, title);
                c_onReceivedTitle(m_id, title);
            }
    
            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback)
            {
                callback.invoke(origin, m_hasLocationPermission, false);
            }
        }
    
        public QtAndroidWebViewController(final Activity activity, final long id)
        {
            m_activity = activity;
            m_id = id;
            final Semaphore sem = new Semaphore(0);
            m_activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    m_webView = new WebView(m_activity);
                    m_hasLocationPermission = hasLocationPermission(m_webView);
                    WebSettings webSettings = m_webView.getSettings();
    
                    if (Build.VERSION.SDK_INT > 10) {
                        try {
                            m_webViewOnResume = m_webView.getClass().getMethod("onResume");
                            m_webViewOnPause = m_webView.getClass().getMethod("onPause");
                            m_webSettingsSetDisplayZoomControls = webSettings.getClass().getMethod("setDisplayZoomControls", boolean.class);
                            if (Build.VERSION.SDK_INT > 18) {
                                m_webViewEvaluateJavascript = m_webView.getClass().getMethod("evaluateJavascript",
                                                                                             String.class,
                                                                                             ValueCallback.class);
                            }
                        } catch (Exception e) { /* Do nothing */ e.printStackTrace(); }
                    }
    
                    //allowing access to location without actual ACCESS_FINE_LOCATION may throw security exception
                    webSettings.setGeolocationEnabled(m_hasLocationPermission);
    
                    webSettings.setJavaScriptEnabled(true);
                    if (m_webSettingsSetDisplayZoomControls != null) {
                        try { m_webSettingsSetDisplayZoomControls.invoke(webSettings, false); } catch (Exception e) { e.printStackTrace(); }
                    }
                    webSettings.setBuiltInZoomControls(true);
                    webSettings.setPluginState(PluginState.ON);
                    m_webView.setWebViewClient((WebViewClient)new QtAndroidWebViewClient());
                    m_webView.setWebChromeClient((WebChromeClient)new QtAndroidWebChromeClient());
                    sem.release();
                }
            });
    
            try {
                sem.acquire();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public void loadUrl(final String url)
        {
            if (url == null) {
                return;
            }
    
            resetLoadingState(STARTED_STATE);
            c_onPageStarted(m_id, url, null);
            m_activity.runOnUiThread(new Runnable() {
                @Override
                public void run() { m_webView.loadUrl(url); }
            });
        }
    
        public void loadData(final String data, final String mimeType, final String encoding)
        {
            if (data =https://www.cnblogs.com/ALittleDruid/p/= null)
                return;
    
            resetLoadingState(STARTED_STATE);
            c_onPageStarted(m_id, null, null);
            m_activity.runOnUiThread(new Runnable() {
                @Override
                public void run() { m_webView.loadData(data, mimeType, encoding); }
            });
        }
    
        public void loadDataWithBaseURL(final String baseUrl,
                                        final String data,
                                        final String mimeType,
                                        final String encoding,
                                        final String historyUrl)
        {
            if (data =https://www.cnblogs.com/ALittleDruid/p/= null)
                return;
    
            resetLoadingState(STARTED_STATE);
            c_onPageStarted(m_id, null, null);
            m_activity.runOnUiThread(new Runnable() {
                @Override
                public void run() { m_webView.loadDataWithBaseURL(baseUrl, data, mimeType, encoding, historyUrl); }
            });
        }
    
        public void goBack()
        {
            m_activity.runOnUiThread(new Runnable() {
                @Override
                public void run() { m_webView.goBack(); }
            });
        }
    
        public boolean canGoBack()
        {
            final boolean[] back = {false};
            final Semaphore sem = new Semaphore(0);
            m_activity.runOnUiThread(new Runnable() {
                @Override
                public void run() { back[0] = m_webView.canGoBack(); sem.release(); }
            });
    
            try {
                sem.tryAcquire(BLOCKING_TIMEOUT, TimeUnit.MILLISECONDS);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return back[0];
        }
    
        public void goForward()
        {
            m_activity.runOnUiThread(new Runnable() {
                @Override
                public void run() { m_webView.goForward(); }
            });
        }
    
        public boolean canGoForward()
        {
            final boolean[] forward = {false};
            final Semaphore sem = new Semaphore(0);
            m_activity.runOnUiThread(new Runnable() {
                @Override
                public void run() { forward[0] = m_webView.canGoForward(); sem.release(); }
            });
    
            try {
                sem.tryAcquire(BLOCKING_TIMEOUT, TimeUnit.MILLISECONDS);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return forward[0];
        }
    
        public void stopLoading()
        {
            m_activity.runOnUiThread(new Runnable() {
                @Override
                public void run() { m_webView.stopLoading(); }
            });
        }
    
        public void reload()
        {
            m_activity.runOnUiThread(new Runnable() {
                @Override
                public void run() { m_webView.reload(); }
            });
        }
    
        public String getTitle()
        {
            final String[] title = {""};
            final Semaphore sem = new Semaphore(0);
            m_activity.runOnUiThread(new Runnable() {
                @Override
                public void run() { title[0] = m_webView.getTitle(); sem.release(); }
            });
    
            try {
                sem.tryAcquire(BLOCKING_TIMEOUT, TimeUnit.MILLISECONDS);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return title[0];
        }
    
        public int getProgress()
        {
            return m_progress;
        }
    
        public boolean isLoading()
        {
            return m_loadingState == LOADING_STATE || m_loadingState == STARTED_STATE || (m_progress > 0 && m_progress < 100);
        }
    
        public void runJavaScript(final String script, final long callbackId)
        {
            if (script == null)
                return;
    
            if (Build.VERSION.SDK_INT < 19 || m_webViewEvaluateJavascript == null)
                return;
    
            m_activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        m_webViewEvaluateJavascript.invoke(m_webView, script, callbackId == -1 ? null :
                            new ValueCallback<String>() {
                                @Override
                                public void onReceiveValue(String result) {
                                    c_onRunJavaScriptResult(m_id, callbackId, result);
                                }
                            });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    
        public String getUrl()
        {
            final String[] url = {""};
            final Semaphore sem = new Semaphore(0);
            m_activity.runOnUiThread(new Runnable() {
                @Override
                public void run() { url[0] = m_webView.getUrl(); sem.release(); }
            });
    
            try {
                sem.tryAcquire(BLOCKING_TIMEOUT, TimeUnit.MILLISECONDS);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            return url[0];
        }
    
        public WebView getWebView()
        {
           return m_webView;
        }
    
        public void onPause()
        {
            if (m_webViewOnPause == null)
                return;
    
            m_activity.runOnUiThread(new Runnable() {
                @Override
                public void run() { try { m_webViewOnPause.invoke(m_webView); } catch (Exception e) { e.printStackTrace(); } }
            });
        }
    
        public void onResume()
        {
            if (m_webViewOnResume == null)
                return;
    
            m_activity.runOnUiThread(new Runnable() {
                @Override
                public void run() { try { m_webViewOnResume.invoke(m_webView); } catch (Exception e) { e.printStackTrace(); } }
            });
        }
    
        private static boolean hasLocationPermission(View view)
        {
            final String name = view.getContext().getPackageName();
            final PackageManager pm = view.getContext().getPackageManager();
            return pm.checkPermission("android.permission.ACCESS_FINE_LOCATION", name) == PackageManager.PERMISSION_GRANTED;
        }
    
        public void destroy()
        {
            m_activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    m_webView.destroy();
                }
            });
        }
    
        public void printToPdf(final String fileName){
            if(!busy){
                busy = true;
                m_activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() { 
                        Html2Pdf html2Pdf = new Html2Pdf();
                        html2Pdf.printToPdf(m_webView, fileName);
                    }
                });
            }else{
                c_onpdfPrintingFinished(m_id,false); 
            }
        }
    
    }

     

 

  1. 主要修改:
    1. 增加了 void printToPdf(final String fileName)列印介面
    2. 增加了 native void c_onpdfPrintingFinished(long id, boolean succeed)作為列印完成的回呼
    3. 增加了內部類Html2Pdf實作列印成PDF
  • 修改$QtSrc/qtwebview/src/plugins/android/qandroidwebview_p.h
  1. 增加槽函式 void printToPdf(const QString &fileName) Q_DECL_OVERRIDE;
  • 修改$QtSrc/qtwebview/src/plugins/android/qandroidwebview.cpp
  1. 實作槽函式
    void QAndroidWebViewPrivate::printToPdf(const QString &fileName)
    {
        const QJNIObjectPrivate &fileNameString = QJNIObjectPrivate::fromString(fileName);
        m_viewController.callMethod<void>("printToPdf","(Ljava/lang/String;)V",fileNameString.object());
    }
  2. 實作java代碼中列印完成的回呼
    static void c_onpdfPrintingFinished(JNIEnv *env,
                                  jobject thiz,
                                  jlong id,
                                  jboolean succeed)
    {
        Q_UNUSED(env)
        Q_UNUSED(thiz)
        const WebViews &wv = (*g_webViews);
        QAndroidWebViewPrivate *wc = wv[id];
        if (!wc)
            return;
        Q_EMIT wc->pdfPrintingFinished(succeed);
    }
  3. 修改JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* /*reserved*/),注冊c_onpdfPrintingFinished回呼函式,
    JNINativeMethod methods[]陣列里增加一項
    {"c_onpdfPrintingFinished","(JZ)V",reinterpret_cast<void *>(c_onpdfPrintingFinished)}

 

  • 修改$QtSrc/qtwebview/src/webview/qabstractwebview_p.h(以下增加的所有的C++代碼、函式、信號等都用#if ANDROID宏條件編譯)
  1. 增加信號void pdfPrintingFinished(bool succeed);
  • 修改$QtSrc/qtwebview/src/webview/qquickwebview_p.h
  1. 增加公開槽函式 void printToPdf(const QString &fileName) Q_DECL_OVERRIDE;
  2. 增加信號 void pdfPrintingFinished(bool succeed);
  3. 增加私有槽函式 void onPdfPrintingFinished(bool succeed);
  • 修改$QtSrc/qtwebview/src/webview/qquickwebview.cpp
  1. 建構式里關聯槽函式和信號
    #if ANDROID
    connect(m_webView, &QWebView::pdfPrintingFinished, this, &QQuickWebView::onPdfPrintingFinished);
    #endif
  2. 實作槽函式printToPdf
    #if ANDROID
    void QQuickWebView::printToPdf(const QString &fileName)
    {
        m_webView->printToPdf(fileName);
    }
    #endif
  3. 實作槽函式onPdfPrintingFinished
    #if ANDROID
    void QQuickWebView::onPdfPrintingFinished(bool succeed)
    {
        Q_EMIT pdfPrintingFinished(succeed);
    }
    #endif
  • 修改$QtSrc/qtwebview/src/webview/qwebviewinterface_p.h
  1. 增加純虛函式 virtual void printToPdf(const QString &fileName) = 0;
  • 修改$QtSrc/qtwebview/src/webview/qwebviewfactory.cpp
  1. QNullWebView類增加
    void printToPdf(const QString &fileName) override
        {Q_UNUSED(fileName); }
  • 修改$QtSrc/qtwebview/src/webview/qwebview_p.h
  1. 增加公開槽函式 void printToPdf(const QString &fileName) Q_DECL_OVERRIDE;
  2. 增加信號 void pdfPrintingFinished(bool succeed);
  3. 增加私有槽函式 void onPdfPrintingFinished(bool succeed);
  • 修改$QtSrc/qtwebview/src/webview/qwebview.cpp
  1. 建構式里關聯槽函式和信號
    #if ANDROID
    connect(d, &QAbstractWebView::pdfPrintingFinished, this, &QWebView::onPdfPrintingFinished);
    #endif
  2. 實作槽函式printToPdf
    #if ANDROID
    void QWebView::printToPdf(const QString &fileName)
    {
        d->printToPdf(fileName);
    }
    #endif
  3. 實作槽函式onPdfPrintingFinished
    #if ANDROID
    void QWebView::onPdfPrintingFinished(bool succeed)
    {
        Q_EMIT pdfPrintingFinished(succeed);
    }
    #endif
  • 在$QtSrc/qtwebview/src/jar目錄下新建lib目錄,將dexmaker-1.2.jar檔案拷貝到該目錄下
  • 修改$QtSrc/qtwebview/src/jar/jar.pro
    TARGET = QtAndroidWebView

    load(qt_build_paths)
    CONFIG += java
    DESTDIR = $$MODULE_BASE_OUTDIR/jar

    JAVACLASSPATH += $$PWD/src \
        $$PWD/lib/dexmaker-1.2.jar

    JAVASOURCES += $$PWD/src/org/qtproject/qt5/android/view/QtAndroidWebViewController.java

    # install
    thridpartyjar.files = \
        $$PWD/lib/dexmaker-1.2.jar
    thridpartyjar.path = $$[QT_INSTALL_PREFIX]/jar

    target.path = $$[QT_INSTALL_PREFIX]/jar
    INSTALLS += target thridpartyjar
  • 修改$QtSrc/qtwebview/src/webview/webview.pro
    ……
    
    QMAKE_DOCS = \
                 $$PWD/doc/qtwebview.qdocconf

    ANDROID_BUNDLED_JAR_DEPENDENCIES = \
        jar/QtAndroidWebView.jar \
        jar/dexmaker-1.2.jar
    ANDROID_PERMISSIONS = \
        android.permission.ACCESS_FINE_LOCATION
    ANDROID_LIB_DEPENDENCIES = \
        plugins/webview/libqtwebview_android.so

    HEADERS += $$PUBLIC_HEADERS $$PRIVATE_HEADERS

    load(qt_module)
  • 修改$QtSrc/qtwebview/src/imports/plugins.qmltypes
  1. 增加信號
    Signal {
                name: "pdfPrintingFinished"
                revision: 1
                Parameter { name: "succeed"; type: "bool" }
            }
  2. 增加方法
    Method {
                name: "printToPdf"
                revision: 1
                Parameter { name: "fileName"; type: "string" }
            }
  • 配置和編譯

  1. ./configure -extprefix $QTInstall/android_arm64_v8a -xplatform android-clang -release -nomake tests -nomake examples -opensource -confirm-license -recheck-all -android-ndk $NDKPATH -android-sdk $AndroidSDKPATH -android-ndk-host linux-x86_64 -android-arch arm64-v8a
    -android-arch支持armeabi, armeabi-v7a, arm64-v8a, x86, x86_64,一次只能編譯一個架構,注意不同架構要修改安裝目錄
  2. make -j8
  3. make install
  • 上述軟體版本
  1. QT:5.13.2
  2. NDK:r20b(20.1.5948944)
  3. Android-buildToolsVersion:29.0.2
  • 使用示例
    import QtQuick 2.12
    import QtQuick.Window 2.12
    import QtWebView 1.1
    import QtQuick.Controls 2.12
    
    Window {
        id: window
        visible: true
        width: 1080
        height: 1920
        title: qsTr("Hello World")
        WebView{
            id:webView
            anchors.bottom: printBtn.top
            anchors.right: parent.right
            anchors.left: parent.left
            anchors.top: parent.top
            anchors.bottomMargin: 0
            url:"http://www.qq.com"
            onPdfPrintingFinished: {
                printBtn.text = "列印" + (succeed?"成功":"失敗")
                printBtn.enabled = true
            }
        }
    
        Button {
            id:printBtn
            text: "列印"
            anchors.bottom: parent.bottom
            anchors.bottomMargin: 0
            onClicked: {
                printBtn.enabled = false
                webView.printToPdf("/sdcard/aaa.pdf")
            }
        }
    }

全部修改見https://github.com/ALittleDruid/qtwebview/commit/722a4757dd0acf86846194607a433cd724e9b028

下期預告:在Android平臺上實作串口讀寫的功能

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/50062.html

標籤:Android

上一篇:安卓AlertDialog四種對話框的最科學撰寫用法

下一篇:IPFS/Filecoin主網即將上線,普通人可以投資嗎?

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【從零開始擼一個App】Dagger2

    Dagger2是一個IOC框架,一般用于Android平臺,第一次接觸的朋友,一定會被搞得暈頭轉向。它延續了Java平臺Spring框架代碼碎片化,注解滿天飛的傳統。嘗試將各處代碼片段串聯起來,理清思緒,真不是件容易的事。更不用說還有各版本細微的差別。 與Spring不同的是,Spring是通過反射 ......

    uj5u.com 2020-09-10 06:57:59 more
  • Flutter Weekly Issue 66

    新聞 Flutter 季度調研結果分享 教程 Flutter+FaaS一體化任務編排的思考與設計 詳解Dart中如何通過注解生成代碼 GitHub 用對了嗎?Flutter 團隊分享如何管理大型開源專案 插件 flutter-bubble-tab-indicator A Flutter librar ......

    uj5u.com 2020-09-10 06:58:52 more
  • Proguard 常用規則

    介紹 Proguard 入口,如何查看輸出,如何使用 keep 設定入口以及使用實體,如何配置壓縮,混淆,校驗等規則。

    ......

    uj5u.com 2020-09-10 06:59:00 more
  • Android 開發技術周報 Issue#292

    新聞 Android即將獲得類AirDrop功能:可向附近設備快速分享檔案 谷歌為安卓檔案管理應用引入可安全隱藏資料的Safe Folder功能 Android TV新主界面將顯示電影、電視節目和應用推薦內容 泄露的Android檔案暗示了傳說中的谷歌Pixel 5a與折疊屏新機 谷歌發布Andro ......

    uj5u.com 2020-09-10 07:00:37 more
  • AutoFitTextureView Error inflating class

    報錯: Binary XML file line #0: Binary XML file line #0: Error inflating class xxx.AutoFitTextureView 解決: <com.example.testy2.AutoFitTextureView android: ......

    uj5u.com 2020-09-10 07:00:41 more
  • 根據Uri,Cursor沒有獲取到對應的屬性

    Android: 背景:呼叫攝像頭,拍攝視頻,指定保存的地址,但是回傳的Cursor檔案,只有名稱和大小的屬性,沒有其他諸如時長,連ID屬性都沒有 使用 cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATIO ......

    uj5u.com 2020-09-10 07:00:44 more
  • Android連載29-持久化技術

    一、持久化技術 我們平時所使用的APP產生的資料,在記憶體中都是瞬時的,會隨著斷電、關機等丟失資料,因此android系統采用了持久化技術,用于存盤這些“瞬時”資料 持久化技術包括:檔案存盤、SharedPreference存盤以及資料庫存盤,還有更復雜的SD卡記憶體儲。 二、檔案存盤 最基本存盤方式, ......

    uj5u.com 2020-09-10 07:00:47 more
  • Android Camera2Video整合到自己專案里

    背景: Android專案里呼叫攝像頭拍攝視頻,原本使用的 MediaStore.ACTION_VIDEO_CAPTURE, 后來因專案需要,改成了camera2 1.Camera2Video 官方demo有點問題,下載后,不能直接整合到專案 問題1.多次拍攝視頻崩潰 問題2.雙擊record按鈕, ......

    uj5u.com 2020-09-10 07:00:50 more
  • Android 開發技術周報 Issue#293

    新聞 谷歌為Android TV開發者提供多種新功能 Android 11將自動填表功能整合到鍵盤輸入建議中 谷歌宣布Android Auto即將支持更多的導航和數字停車應用 谷歌Pixel 5只有XL版本 搭載驍龍765G且將比Pixel 4更便宜 [圖]Wear OS將迎來重磅更新:應用啟動時間 ......

    uj5u.com 2020-09-10 07:01:38 more
  • 海豚星空掃碼投屏 Android 接收端 SDK 集成 六步驟

    掃碼投屏,開放網路,獨占設備,不需要額外下載軟體,微信掃碼,發現設備。支持標準DLNA協議,支持倍速播放。視頻,音頻,圖片投屏。好點意思。還支持自定義基于 DLNA 擴展的操作動作。好像要收費,沒體驗。 這里簡單記錄一下集成程序。 一 跟目錄的build.gradle添加私有mevan倉庫 mave ......

    uj5u.com 2020-09-10 07:01:43 more
最新发布
  • 歡迎頁輪播影片

    如圖,引導開始,球從上落下,同時淡入文字,然后文字開始輪播,最后一頁時停止,點擊進入首頁。 在來看看效果圖。 重力球先不講,主要歡迎輪播簡單實作 首先新建一個類 TextTranslationXGuideView,用于影片展示 文本是類似的,最后會有個圖片箭頭影片,布局很簡單,就是一個 TextVi ......

    uj5u.com 2023-04-20 08:40:31 more
  • 【FAQ】關于華為推送服務因營銷訊息頻次管控導致服務通訊類訊息

    一. 問題描述 使用華為推送服務下發IM訊息時,下發訊息請求成功且code碼為80000000,但是手機總是收不到訊息; 在華為推送自助分析(Beta)平臺查看發現,訊息發送觸發了頻控。 二. 問題原因及背景 2023年1月05日起,華為推送服務對咨詢營銷類訊息做了單個設備每日推送數量上限管理,具體 ......

    uj5u.com 2023-04-20 08:40:11 more
  • 歡迎頁輪播影片

    如圖,引導開始,球從上落下,同時淡入文字,然后文字開始輪播,最后一頁時停止,點擊進入首頁。 在來看看效果圖。 重力球先不講,主要歡迎輪播簡單實作 首先新建一個類 TextTranslationXGuideView,用于影片展示 文本是類似的,最后會有個圖片箭頭影片,布局很簡單,就是一個 TextVi ......

    uj5u.com 2023-04-20 08:39:36 more
  • 【FAQ】關于華為推送服務因營銷訊息頻次管控導致服務通訊類訊息

    一. 問題描述 使用華為推送服務下發IM訊息時,下發訊息請求成功且code碼為80000000,但是手機總是收不到訊息; 在華為推送自助分析(Beta)平臺查看發現,訊息發送觸發了頻控。 二. 問題原因及背景 2023年1月05日起,華為推送服務對咨詢營銷類訊息做了單個設備每日推送數量上限管理,具體 ......

    uj5u.com 2023-04-20 08:39:13 more
  • iOS從UI記憶體地址到讀取成員變數(oc/swift)

    開發除錯時,我們發現bug時常首先是從UI顯示發現例外,下一步才會去定位UI相關連的資料的。XCode有給我們提供一系列debug工具,但是很多人可能還沒有形成一套穩定的除錯流程,因此本文嘗試解決這個問題,順便提出一個暴論:UI顯示例外問題只需要兩個步驟就能完成定位作業的80%: 定位例外 UI 組 ......

    uj5u.com 2023-04-19 09:16:23 more
  • FIDE重磅更新!性能飛躍!體驗有禮!

    FIDE 開發者工具重構升級啦!實作500%性能提升,誠邀體驗! 一直以來不少開發者朋友在社區反饋,在使用 FIDE 工具的程序中,時常會遇到諸如加載不及時、代碼預覽/渲染性能不如意的情況,十分影響開發體驗。 作為技術團隊,我們深知一件趁手的開發工具對開發者的重要性,因此,在2023年開年,FinC ......

    uj5u.com 2023-04-19 09:16:15 more
  • 游戲內嵌社區服務開放,助力開發者提升玩家互動與留存

    華為 HMS Core 游戲內嵌社區服務提供快速訪問華為游戲中心論壇能力,支持玩家直接在游戲內瀏覽帖子和交流互動,助力開發者擴展內容生產和觸達的場景。 一、為什么要游戲內嵌社區? 二、游戲內嵌社區的典型使用場景 1、游戲內打開論壇 您可以在游戲內繪制論壇入口,為玩家提供沉浸式發帖、瀏覽、點贊、回帖、 ......

    uj5u.com 2023-04-19 09:15:46 more
  • iOS從UI記憶體地址到讀取成員變數(oc/swift)

    開發除錯時,我們發現bug時常首先是從UI顯示發現例外,下一步才會去定位UI相關連的資料的。XCode有給我們提供一系列debug工具,但是很多人可能還沒有形成一套穩定的除錯流程,因此本文嘗試解決這個問題,順便提出一個暴論:UI顯示例外問題只需要兩個步驟就能完成定位作業的80%: 定位例外 UI 組 ......

    uj5u.com 2023-04-19 09:14:53 more
  • FIDE重磅更新!性能飛躍!體驗有禮!

    FIDE 開發者工具重構升級啦!實作500%性能提升,誠邀體驗! 一直以來不少開發者朋友在社區反饋,在使用 FIDE 工具的程序中,時常會遇到諸如加載不及時、代碼預覽/渲染性能不如意的情況,十分影響開發體驗。 作為技術團隊,我們深知一件趁手的開發工具對開發者的重要性,因此,在2023年開年,FinC ......

    uj5u.com 2023-04-19 09:14:08 more
  • 游戲內嵌社區服務開放,助力開發者提升玩家互動與留存

    華為 HMS Core 游戲內嵌社區服務提供快速訪問華為游戲中心論壇能力,支持玩家直接在游戲內瀏覽帖子和交流互動,助力開發者擴展內容生產和觸達的場景。 一、為什么要游戲內嵌社區? 二、游戲內嵌社區的典型使用場景 1、游戲內打開論壇 您可以在游戲內繪制論壇入口,為玩家提供沉浸式發帖、瀏覽、點贊、回帖、 ......

    uj5u.com 2023-04-19 09:08:34 more