def structure_to_pdb_string(structure):
    """Converts a :py:class:`.AtomStructure` to a .pdb filestring.

    :param AtomStructure structure: the structure to convert.
    :rtype: ``str``"""

    lines = []
    pack_sequences(structure, lines)
    atoms = sorted(structure.atoms(), key=lambda a: a.id)
    for i, atom in enumerate(atoms):
        atom_to_atom_line(atom, lines)
        if isinstance(atom.het, Residue) and (
         atom is atoms[-1] or atoms[i + 1].chain is not atom.chain or
          isinstance(atoms[i + 1].het, Ligand)):
            last = lines[-1]
            lines.append(f"TER   {last[6:11]}      {last[17:20]} {last[21]}{last[22:26]}{last[26]}")
    return "\n".join(lines)