Beispiel #1
0
    def save_all_pdf(self, view_item, view_name, filter_file_name):
        if view_item is None:
            return

        filter_values, filter_names = self.get_filter_values(filter_file_name)

        for value in filter_values:
            pdf_req_option = TSC.PDFRequestOptions(
                page_type=TSC.PDFRequestOptions.PageType.A3,
                orientation=TSC.PDFRequestOptions.Orientation.Portrait,
                maxage=1)
            file_name = ""
            for i in range(len(filter_names)):
                filter_name = filter_names[i]
                file_name = file_name + '-' + str(
                    value[filter_name.get('pos')].strip())
                pdf_req_option.vf(filter_name.get('name'),
                                  value[filter_name.get('pos')].strip())

            self.server.views.populate_pdf(view_item, pdf_req_option)

            if not os.path.exists('pdf/' + view_name):
                os.makedirs('pdf/' + view_name)

            with open('./pdf/' + view_name + '/file-' + file_name + '.pdf',
                      'wb') as f:
                self.add_item_logs("Saving file {} for view {} ".format(
                    view_name + file_name, view_name))
                f.write(view_item.pdf)
Beispiel #2
0
    def download_pdf(self, student_id, grade, name):
        view_name = "PDF Generator"
        with self.server.auth.sign_in(self.tableau_auth):
            req_option = TSC.RequestOptions()
            req_option.filter.add(
                TSC.Filter(
                    TSC.RequestOptions.Field.Name,
                    TSC.RequestOptions.Operator.Equals,
                    view_name,
                ))
            all_views, pagination_item = self.server.views.get(req_option)
            if not all_views:
                raise LookupError(
                    "View with the specified name was not found.")
            view = all_views[0]

            pdf_req_option = TSC.PDFRequestOptions(
                orientation=TSC.PDFRequestOptions.Orientation.Portrait,
                maxage=1,
                page_type=TSC.PDFRequestOptions.PageType.Letter,
            )

            pdf_req_option.vf("StudentID", student_id)
            self.server.views.populate_pdf(view, pdf_req_option)

            filename = f"output/profile_{grade}_{name}_{student_id}.pdf"
            with open(filename, "wb") as pdf_file:
                pdf_file.write(view.pdf)
Beispiel #3
0
    def test_vf_legacy(self) -> None:
        self.server.version = "3.6"
        with requests_mock.mock() as m:
            m.get(requests_mock.ANY)
            url = self.baseurl + "/views/456/data"
            opts = TSC.PDFRequestOptions()
            opts.vf("name1@", "value1")
            opts.vf("name2$", "value2")
            opts.page_type = TSC.PDFRequestOptions.PageType.Tabloid

            resp = self.server.workbooks.get_request(url, request_object=opts)
            self.assertTrue(re.search("vf_name1@=value1", resp.request.query))
            self.assertTrue(re.search("vf_name2\\$=value2",
                                      resp.request.query))
            self.assertTrue(re.search("type=tabloid", resp.request.query))
    def test_populate_pdf(self):
        with open(POPULATE_PDF, 'rb') as f:
            response = f.read()
        with requests_mock.mock() as m:
            m.get(self.baseurl + '/d79634e1-6063-4ec9-95ff-50acbf609ff5/pdf?type=letter&orientation=portrait',
                  content=response)
            single_view = TSC.ViewItem()
            single_view._id = 'd79634e1-6063-4ec9-95ff-50acbf609ff5'

            size = TSC.PDFRequestOptions.PageType.Letter
            orientation = TSC.PDFRequestOptions.Orientation.Portrait
            req_option = TSC.PDFRequestOptions(size, orientation)

            self.server.views.populate_pdf(single_view, req_option)
            self.assertEqual(response, single_view.pdf)
Beispiel #5
0
    def test_vf(self):
        with requests_mock.mock() as m:
            m.get(requests_mock.ANY)
            url = self.baseurl + "/views/456/data"
            opts = TSC.PDFRequestOptions()
            opts.vf("name1#", "value1")
            opts.vf("name2$", "value2")
            opts.page_type = TSC.PDFRequestOptions.PageType.Tabloid

            resp = self.server.workbooks.get_request(url, request_object=opts)
            self.assertTrue(re.search('vf_name1%23=value1',
                                      resp.request.query))
            self.assertTrue(re.search('vf_name2%24=value2',
                                      resp.request.query))
            self.assertTrue(re.search('type=tabloid', resp.request.query))
    def test_populate_pdf(self):
        self.server.version = "3.4"
        self.baseurl = self.server.workbooks.baseurl
        with open(POPULATE_PDF, "rb") as f:
            response = f.read()
        with requests_mock.mock() as m:
            m.get(self.baseurl + "/1f951daf-4061-451a-9df1-69a8062664f2/pdf?type=a5&orientation=landscape",
                  content=response)
            single_workbook = TSC.WorkbookItem('test')
            single_workbook._id = '1f951daf-4061-451a-9df1-69a8062664f2'

            type = TSC.PDFRequestOptions.PageType.A5
            orientation = TSC.PDFRequestOptions.Orientation.Landscape
            req_option = TSC.PDFRequestOptions(type, orientation)

            self.server.workbooks.populate_pdf(single_workbook, req_option)
            self.assertEqual(response, single_workbook.pdf)
Beispiel #7
0
 def generate_pdf(logger, server, args):
     view_url = GetUrl.get_view_url(args.url)
     try:
         view_item: TSC.ViewItem = GetUrl.get_view_by_content_url(
             logger, server, view_url)
         logger.debug(
             _("content_type.view") + ": {}".format(view_item.name))
         req_option_pdf = TSC.PDFRequestOptions(maxage=1)
         server.views.populate_pdf(view_item, req_option_pdf)
         filename = GetUrl.filename_from_args(args.filename, view_item.name,
                                              "pdf")
         with open(filename, "wb") as f:
             f.write(view_item.pdf)
         logger.info(_("export.success").format(view_item.name, filename))
     except TSC.ServerResponseError as e:
         GetUrl.exit_with_error(
             logger, _("publish.errors.unexpected_server_response"), e)
    def test_vf(self):
        with requests_mock.mock() as m:
            m.get(requests_mock.ANY)
            url = "http://test/api/2.3/sites/123/views/456/data"
            opts = TSC.PDFRequestOptions()
            opts.vf("name1#", "value1")
            opts.vf("name2$", "value2")
            opts.page_type = TSC.PDFRequestOptions.PageType.Tabloid

            resp = self.server.workbooks._make_request(
                requests.get,
                url,
                content=None,
                request_object=opts,
                auth_token='j80k54ll2lfMZ0tv97mlPvvSCRyD0DOM',
                content_type='text/xml')
            self.assertTrue(re.search('vf_name1%23=value1',
                                      resp.request.query))
            self.assertTrue(re.search('vf_name2%24=value2',
                                      resp.request.query))
            self.assertTrue(re.search('type=tabloid', resp.request.query))
Beispiel #9
0
def printPDF():

    if request.method == 'POST':
        print("Detected POST method!")
        results = request.form
        print("\nResults from HTML form -> ", results)

        stateResult = results['stateFilter']
        print("\nState Filter -> ", stateResult)

        subCResult = results['subCFilter']
        print("\nsub-Category Filter -> ", subCResult)

    tableau_auth = TSC.TableauAuth('admin', 'admin')
    server = TSC.Server(
        'http://192.168.0.11', use_server_version=True
    )  #use_server_version = True gives us the latest REST API version to work with

    #sign in to Tableau Server and do the things below
    with server.auth.sign_in(tableau_auth):
        #show REST API sevrer version
        tableau_server_version = server.version
        print('\nTableau Server Version:', server.version,
              '\n')  #3.4 is 2019.2

        print('\nGET ALL THE VIEWS ACROSS ALL THE WORKBOOKS >>>')
        print('All the Views (Pager): ')
        for view in TSC.Pager(server.views):
            print(
                "View name: ", view.name, " and View ID: ", view.id
            )  #this line repeats for every View available - thats why they are printed one after another

        # set the PDF request options
        pdf_req_option = TSC.PDFRequestOptions(
            page_type=TSC.PDFRequestOptions.PageType.A4,
            orientation=TSC.PDFRequestOptions.Orientation.Landscape)

        # (optional) set a view filter
        pdf_req_option.vf('State', 'Alabama')

        # print PDF
        for view in TSC.Pager(server.views):
            if view.id == '88aa3d1f-f294-4af4-be1a-bc70b0242526':
                server.views.populate_pdf(view, pdf_req_option)
                with open('./view_pdf.pdf', 'wb') as f:
                    f.write(view.pdf)

        #get this from the database table you are using as filter (dimension) in Tableau
        # if you need more granular have filters for each level of granularity you need
        #stateFilter = ['Alabama', 'Arizona','Arkansas','California','Colorado','Iowa','Kansas','Texas']
        #subCategory = ['Chairs', 'Art', 'Machines', 'Phones']

        stateFilter = [stateResult]
        subCategory = [subCResult]

        # lets filter only for the State
        for state in stateFilter:
            pdf_req_option = TSC.PDFRequestOptions(
                page_type=TSC.PDFRequestOptions.PageType.A4,
                orientation=TSC.PDFRequestOptions.Orientation.Landscape)
            pdf_req_option.vf('State', state)
            print("Printing PDF -->", "view_pdf - " + state + " -.pdf")

            for view in TSC.Pager(server.views):
                if view.id == '88aa3d1f-f294-4af4-be1a-bc70b0242526':
                    server.views.populate_pdf(view, pdf_req_option)
                    with open('./view_pdf - ' + state + ' -.pdf', 'wb') as f:
                        f.write(view.pdf)

        #now lets filter for each State and Sub-Category
        for state in stateFilter:
            for subC in subCategory:
                pdf_req_option = TSC.PDFRequestOptions(
                    page_type=TSC.PDFRequestOptions.PageType.A4,
                    orientation=TSC.PDFRequestOptions.Orientation.Landscape)
                pdf_req_option.vf('State', state)
                pdf_req_option.vf('Sub-Category', subC)
                print("Printing PDF -->",
                      "view_pdf - " + state + " and subCat " + subC + " -.pdf")

                for view in TSC.Pager(server.views):
                    if view.id == '88aa3d1f-f294-4af4-be1a-bc70b0242526':
                        server.views.populate_pdf(view, pdf_req_option)
                        with open(
                                './view_pdf - ' + state + ' - ' + subC +
                                ' -.pdf', 'wb') as f:
                            f.write(view.pdf)

    return render_template('printPDF.html')
Beispiel #10
0
def CSV_ImageRequest(server, tableau_auth, csv_filename, end_file_directory,
                     WorkbookName, DashboardName, UserEmail):

    with server.auth.sign_in(tableau_auth):

        folderExplore.TableauFolderViews(server)

        req_option1 = TSC.RequestOptions()
        req_option1.filter.add(
            TSC.Filter(TSC.RequestOptions.Field.Name,
                       TSC.RequestOptions.Operator.Equals, DashboardName))

        req_option2 = TSC.RequestOptions()
        req_option2.filter.add(
            TSC.Filter(TSC.RequestOptions.Field.Name,
                       TSC.RequestOptions.Operator.Equals, WorkbookName))

        all_views_filtered, views_items1 = server.views.get(req_option1)
        all_workbooks_filtered, workbooks_items1 = server.workbooks.get(
            req_option2)

        view_i, workbook_i = folderExplore.checkMatch(all_views_filtered,
                                                      views_items1,
                                                      all_workbooks_filtered,
                                                      workbooks_items1)

        with open(csv_filename) as csv_file:
            csv_reader = csv.reader(csv_file, delimiter=',')
            line_count = 0

            for row in csv_reader:
                if line_count == 0:
                    num_col = len(row)
                    column_header = row
                    print("\n {}".format(column_header))
                    line_count += 1
                else:
                    if (row[1] == "PNG" or row[1] == "JPG"):

                        # view item is the dashboard view.
                        view_item = all_views_filtered[view_i]

                        image_req_option = TSC.ImageRequestOptions(
                            imageresolution=TSC.ImageRequestOptions.Resolution.
                            High)

                        # Assumes col 0,1,2 are imageName, FileType, and Email respectively

                        for iter_ in range(3, num_col):
                            # column_header[iter_] takes the nth item across in column header,
                            # row header [iter_] takes the same nth item acrpss in the row
                            # pases it to like this:
                            # image_req_option.vf( Color By , 2)
                            # image_req_option.vf( Bubble Color, 1)
                            # image_req_option.vf( Sales Channel, Channel1)
                            if (row[iter_] == "All"):
                                image_req_option.view_filters.clear()
                                break
                            else:
                                image_req_option.vf(column_header[iter_],
                                                    row[iter_])

                        server.views.populate_image(view_item,
                                                    image_req_option)
                        image_filepath = view_item.name

                        with open(
                                end_file_directory + "/" + image_filepath +
                                row[0] + "." + row[1], "wb") as image_file:
                            image_file.write(view_item.image)

                    elif (row[1] == "PDF"):

                        view_item = all_views_filtered[view_i]

                        pdf_req_option = TSC.PDFRequestOptions(
                            page_type=TSC.PDFRequestOptions.PageType.A4,
                            orientation=TSC.PDFRequestOptions.Orientation.
                            Portrait)

                        # Assumes col 0,1,2 are imageName, FileType, and Email respectively
                        for iter_ in range(3, num_col):
                            if (row[iter_] == "All"):
                                pdf_req_option.view_filters.clear()
                                break
                            else:
                                pdf_req_option.vf(column_header[iter_],
                                                  row[iter_])

                        server.views.populate_pdf(view_item, pdf_req_option)
                        pdf_name = view_item.name

                        with open(
                                end_file_directory + "/" + pdf_name + row[0] +
                                "." + row[1], "wb") as pdf_file:
                            pdf_file.write(view_item.pdf)

                            # full_path = end_file_directory + "/" + pdf_name + row[0] + "." + row[1]
                            # emailScript.email_singlePDF(row[2], full_path, row[0], UserEmail)

                    print(row)
                    line_count += 1

            print(f'Processed {line_count} lines.')

    server.auth.sign_out()
Beispiel #11
0
def download_view_pdf(resource_name,
                      project_name,
                      server_url=None,
                      username=None,
                      password=None,
                      path=None,
                      server=None,
                      orientation='portrait',
                      filter_key=None,
                      filter_value=None):
    """
    Download a view as PDF.
    Authetication happens by either passing the credentials (username, pass-
    word and server_url) or the server object when previosly authenticated.

    Parameters:
    resource_name   -- name of the resource to download
    project_name    -- name of the project the resource is stored in
    server_url      -- the url of the server to connect with
    username        -- username of the user to authenticate with
    password        -- password of the user to authenticate with
    server          -- the server object if authenticated previosly
    path            -- path of the resource to download to (default: cwd)
    orientation     -- orientation of the PDF ('portrait'/'landscape')
    filter_key      -- the key the view will get filtered on
    filter_value    -- the value of the filter

    Return value(s):
    file_path       -- path of the downlaoded PDF

    Exception(s):
    NameError       -- Invalid orientation
    """

    # check if the either all the necessary credentials or the server object
    # are there and authenticate if necessary
    server, sign_out = check_credentials_authenticate(username, password,
                                                      server_url, server)
    # get id and object
    resource_id, resource_object = get_resource_id("view",
                                                   resource_name,
                                                   project_name=None,
                                                   server=server)
    # set landscape orientation for the pdf
    if orientation == 'landscape':
        orientation_req = TSC.PDFRequestOptions.Orientation.Landscape
    # set portrait orientation for the pdf
    elif orientation == 'portrait':
        orientation_req = TSC.PDFRequestOptions.Orientation.Portrait
    else:
        raise NameError("Invalid orientation '{}'".format(orientation))
    # set the PDF request options
    page_type = TSC.PDFRequestOptions.PageType.A4
    pdf_req_option = TSC.PDFRequestOptions(page_type=page_type,
                                           orientation=orientation_req)
    # (optional) set a view filter
    if filter_key and filter_value:
        pdf_req_option.vf(filter_key, filter_value)
    # retrieve the PDF for a view
    server.views.populate_pdf(resource_object, pdf_req_option)
    # get path
    if path is None:
        path = os.getcwd() + "/" + resource_object.name + ".pdf"
    # write to disk
    with open(path, "wb") as image_file:
        image_file.write(resource_object.pdf)
    if sign_out is True:
        # sign out from server
        server.auth.sign_out()
    return (path)
Beispiel #12
0
tableau_auth = TSC.TableauAuth('admin', 'admin', user_id_to_impersonate='223510e8-3bf5-4971-bf00-b2146092b957')
server = TSC.Server('http://192.168.0.11', use_server_version = True) #use_server_version = True gives us the latest REST API version to work with
    
#sign in to Tableau Server and do the things below
with server.auth.sign_in(tableau_auth): 
    #show REST API sevrer version
    tableau_server_version =  server.version
    print('\nTableau Server Version:', server.version,'\n') #3.4 is 2019.2

    print('\nGET ALL THE VIEWS ACROSS ALL THE WORKBOOKS >>>')
    print('All the Views (Pager): ')
    for view in TSC.Pager(server.views):
        print("View name: ", view.name, " and View ID: ", view.id)  #this line repeats for every View available - thats why they are printed one after another
    
    # set the PDF request options
    pdf_req_option = TSC.PDFRequestOptions(page_type=TSC.PDFRequestOptions.PageType.A4, orientation=TSC.PDFRequestOptions.Orientation.Landscape)

    # (optional) set a view filter
    pdf_req_option.vf('State', 'Alabama')

    # print PDF
    for view in TSC.Pager(server.views):
        if view.id == '88aa3d1f-f294-4af4-be1a-bc70b0242526':
            server.views.populate_pdf(view, pdf_req_option)
            with open('./view_pdf.pdf', 'wb') as f:
                f.write(view.pdf)

    #get this from the database table you are using as filter (dimension) in Tableau 
    # if you need more granular have filters for each level of granularity you need
    stateFilter = ['Alabama', 'Arizona','Arkansas','California','Colorado','Iowa','Kansas','Texas']
    subCategory = ['Chairs', 'Art', 'Machines', 'Phones']
Beispiel #13
0
 def download_view_pdf(server, view_item):
     pdf = TSC.PDFRequestOptions(maxage=1)
     server.views.populate_pdf(view_item, pdf)
     return view_item.pdf
Beispiel #14
0
 def download_wb_pdf(server, workbook_item):
     pdf = TSC.PDFRequestOptions(maxage=1)
     server.workbooks.populate_pdf(workbook_item, pdf)
     return workbook_item.pdf
Beispiel #15
0
def download_view_pdf(resource_name,
                      project_name,
                      server_url=None,
                      username=None,
                      password=None,
                      path=None,
                      server=None,
                      orientation='portrait',
                      filter_key=None,
                      filter_value=None):
    """
    Download a view as PDF

    Parameters:
    resource_name   -- name of the resource to download - REQ
    project_name    -- name of the project the resource is stored in - REQ
    server_url      -- the url of the server to connect with - SEMI-OPTIONAL (either server or username, password and server_url)
    username        -- username of the user to authenticate with - SEMI-OPTIONAL (either server or username, password and server_url)
    password        -- password of the user to authenticate with - SEMI-OPTIONAL (either server or username, password and server_url)
    server          -- the server object if authenticated previosly - SEMI-OPTIONAL (either server or username, password and server_url)
    path            -- path of the resource to download to (default: cwd) - OPT
    orientation     -- orientation of the PDF ('portrait'/'landscape') - OPT
    filter_key      -- the key the view will get filtered on - OPT
    filter_value    -- the value of the filter - OPT

    Return value(s):
    file_path       -- path of the downlaoded PDF

    Exception(s):
    NameError       -- Invalid orientation
    """

    # check if the either all the necessary credentials or the server object are there and authenticate if necessary
    server = check_credentials_authenticate(username, password, server_url,
                                            server)
    # get id and object
    resource_id, resource_object = get_resource_id("view",
                                                   resource_name,
                                                   project_name=None,
                                                   server=server)
    # set landscape orientation for the pdf
    if orientation == 'landscape':
        orientation_req = TSC.PDFRequestOptions.Orientation.Landscape
    # set portrait orientation for the pdf
    elif orientation == 'portrait':
        orientation_req = TSC.PDFRequestOptions.Orientation.Portrait
    else:
        raise NameError("Invalid orientation '{}'".format(orientation))
    # set the PDF request options
    pdf_req_option = TSC.PDFRequestOptions(
        page_type=TSC.PDFRequestOptions.PageType.A4,
        orientation=orientation_req)
    # (optional) set a view filter
    if filter_key and filter_value:
        pdf_req_option.vf(filter_key, filter_value)
    # retrieve the PDF for a view
    server.views.populate_pdf(view_item, pdf_req_option)
    file_path = server.workbooks.download(resource_id,
                                          path,
                                          include_extract=extract,
                                          no_extract=None)
    return (file_path)