web123456

Qt of export PDF, HTML and Word (a)

Executive Summary:
1, the basic principle of Qt export file;
2, QPrinter, HTML and PDF;
3, HTML editor;
4, HTML and Word;
5, qwt picture and pdf export

First, the basic principles of Qt drawing and export files
Qt's 2D graphics engine is based on the QPainter class.QPainter draws both geometric shapes (points, lines, rectangles, ellipses, arcs, chordal rows, pie charts, polygons, and Bezier curves), as well as pixel maps, images, and text. (Refer to "C++ GUI Programming with Qt")
See the Qt help file for a description of "QPainter":
The QPainter class performs low-level painting on widgets and other paint devices.
QPainter provides highly optimized functions to do most of the drawing GUI programs require. It can draw everything from simple lines to complex shapes like pies and chords. It can also draw aligned text and pixmaps. Normally, it draws in a "natural" coordinate system, but it can also do view and world transformation. QPainter can operate on any object that inherits the QPaintDevice class.
The common use of QPainter is inside a widget's paint event: Construct and customize (. set the pen or the brush) the painter. Then draw. Remember to destroy the QPainter object after drawing. 
 QPainter can paint on any "drawing device" (class inherited from QPaintDevice), such as QWidget, QPixmap, QImage, QSvgGenerator and so on. To paint on a drawing device, simply create a QPainter object and pass a pointer to the device to paint on its paintEvent.
QPainter can also be used with QPrinter to print files and create PDF documents. Check the Qt help file for the following description of "QPrinter":
The QPrinter class is a paint device that paints on a printer.
This device represents a series of pages of printed output, and is used in almost exactly the same way as other paint devices such as QWidget and QPixmap. A set of additional functions are provided to manage device-specific features, such as orientation and resolution, and to step through the pages in a document as it is generated.
QPrinter It is essentially a drawing device, and drawing on QPrinter is very similar to drawing on other devices, except for some device-related management functions. (Refer to "C++ GUI Programming with Qt" and the Qt of the generation of PDF ) QPrinter can set up two output formats: QPrinter::NativeFormat and QPrinter::PdfFormat, the former is a direct print, the latter is exported as a pdf document.

Two, QPrinter Export PDF
Note: To use QPrinter, you need to "QT += printsupport" in the .pro file.
1, export images (refer to the blog post " Qt of the generation of PDF”)
QPrinter printer_pixmap(QPrinter::HighResolution);
printer_pixmap.setPageSize(QPrinter::A4);   //Set the paper size to A4
printer_pixmap.setOutputFormat(QPrinter::PdfFormat);   //Set the output format to pdf
printer_pixmap.setOutputFileName("E:\\test_pixmap.pdf");   //Set the output path
QPixmap pixmap = QPixmap::grabWidget(main_widget, main_widget->rect());   // Get the picture of the interface

QPainter painter_pixmap;     // Use QPainter to draw on the drawing device
painter_pixmap.begin(&printer_pixmap);
QRect rect = painter_pixmap.viewport();
int multiple = ()/();
painter_pixmap.scale(multiple, multiple); //scale the image (everything to be painted) multiple-1x on the pdf
painter_pixmap.drawPixmap(0, 0, pixmap);   // Call the corresponding function in QPainter to draw the diagram.
painter_pixmap.end();

2, Generate text (Refer to blog post " Qt of the generation of PDF ”)
The difference is to call QPainter's drawText() function. In addition, you need to call QPrinter's newPage() function to manually paginate.

3, Generate HTML (Refer to blog post " Qt of the generation of PDF ”)
For a single page of the document, you can use the above two methods, for multi-page complex documents, in order to avoid paging and other trouble, a way to use HTML to PDF. The following gives a simple example.
To create a new console project using QCreator, first add the following to the .pro file "QT += printsupport"; then follow the blog post Qt of the generation of PDF Modify the main file.
The main process is:
First, edit HTML and save it to a QString, then use Qt's rich text engine QTextDocument to support the "rich text" feature, set the QString to html format (retaining the html feature), and finally use the QTextDocument associated with QPrinter.

Third, QFile + QString direct export HTML file
Refer to "stockchart" in QWT's examples, you can export the interface to html directly, the key code is as follows:
void Plot::report()
{
    QString strInfor;
    QString strDataDirectory = "Data";
    QString path(QDir::currentPath());
    QDir dir(QDir::currentPath());
    if (!(strDataDirectory))   // Determine if the Data directory exists
    {
        strInfor = strDataDirectory + tr(" is not exist!", "need translate");
        return;
    }

    QString strReportDirectoryName = QDateTime::currentDateTime().toString("yyyy-MM-dd_hh-mm-ss"); //Get the current time of the system and format it
    (strReportDirectoryName);
    if (!(strReportDirectoryName))   // Determine if the Report directory exists
    {
        strInfor = strDataDirectory + "\\" + strReportDirectoryName + tr(" is not exist!", "need translate");;
        return;
    }

    QString strImageDirectoryName = "Images";
    (strImageDirectoryName);
    if (!(strImageDirectoryName))   // Determine if the Image directory in the Report exists.
    {
        strInfor = strDataDirectory + "\\" + strReportDirectoryName + "\\" + strImageDirectoryName + tr(" is not exist!", "need translate");;
        return;
    }

    QString strImagePath = strDataDirectory + "\\" + strReportDirectoryName + "\\" + strImageDirectoryName;
    QString strImangeFileName = strImagePath + "\\" + "";
    QSizeF tmp(300, 200);
    QwtPlotRenderer renderer;
    (this, strImangeFileName, tmp);
    //(this, "./Debug/", tmp);

    QString strHtmlReportPath = strDataDirectory + "\\" + strReportDirectoryName;
    QString strHtmlReportFileName = strHtmlReportPath + "\\" + "";

    QFile report(strHtmlReportFileName);
    (QIODevice::WriteOnly | QIODevice::Truncate);
    QTextStream ofs(&report);

    // Write header data to HTML file
    QString strHeadHtml = "\n\n\n";
    strHeadHtml += "\n";
    strHeadHtml += GetReturnTopScript();
    strHeadHtml += "\n\n";
    ofs << strHeadHtml;

    // Write configuration and image data to HTML files
    QString strImageHtml;
strImageHtml += "

" + QObject::tr("Picture ", "need translate") \
        + ": " + "stockchart" + "

\n";
      strImageHtml += "

Qt之导出PDF、HTML和Word(一)
                    + "stockchart" + ".bmp\" title=\"" + "stockchart" + "\" alt=\"" + "stockchart" + "\" />

\n";
      strImageHtml += "

 

";
    ofs << strImageHtml;

    // Write trailing data to HTML file
    ofs << QString("\n");

    ();
}
Note: It mainly applies QString splicing to export individual variables and image links to HTML files.

IV. HTML editor
In the project, whether it is exported to PDF or export HTML, the core content is written in HTML files. So here is a quick and easy way to edit HTML.
1, download and install a "DreamWeaver".
2, open "DreamWeaver", create an "html" project.


You can visualize the design in "Design Mode", then switch to "Code Mode" to copy the code and convert it to QString. You can also reverse the operation, copy the code to "Code Mode", then switch to "Design Mode" for editing.

3, you can directly drag and drop the control, and then just do it in the properties below.


4, there is a simple conversion from html to C++ code:
while (() == 0) {
            QString strBuf = ();
            ("\\r\\n");
            ("\"", "\\\"");
            streamOut<<m_strPrefix<<"\""<<strBuf<<"\";"<<endl;
        }
Mainly: adding line breaks for ease of reading and writing, and recognition of escape characters. In addition, the prefix is "html +=", which is mainly the right value of the statement.